30/09/2018, 23:10

File handling với c++/ Visual studio

Mình có đoạn code sau đang thắc mắc

#include <stdio.h>
#include <string.h>
struct Books
{
    int code;
    char name[55];
};
int read(Books *lstBooks, int *p, const char *fileName){
    FILE *f;
    int result = 0;
    f = fopen(fileName, "rb");
    if(f!=NULL)
    {
        fread(p, sizeof(int), 1, f);
        if(*p > 0){
            fread(lstBooks, sizeof(Books), *p, f);
            result = 1;
        }
        fclose(f);
    }
    else
    {
      printf("CANT READ FILE");
  }
  return result;
}
int write(Books *lstBooks, int count, const char *fileName){
    FILE *f;
    int result = 0;
    f = fopen(fileName, "wb");
    if(f!=NULL)
    {
        fwrite(&count, sizeof(int), 1, f);
        fwrite(lstBooks, sizeof(Books), count, f);
        fclose(f);
        result = 1;
    }
    else
    {
      printf("CANT READ FILE");
  }
  return result;
}
int main( ) {
    Books books[10];
    int count = 0;
    read(books, &count, "books.dat");
    books[count].code = count+1;
    strcpy(books[count].name,"Book");
    count++;
    write(books, count, "books.dat");
    for(int i=0; i<count;i++)
    {
      printf("Code: %d", books[i].code);
      puts(books[i].name);
  }
  return 0;
}

Ở hai hàm read và write theo như code này thì đầu tiên sẽ kiếm file có tên books.dat, nếu ko có thì tạo cái mới. Và nếu có rồi thì sẽ tạo cái mới đè lên cái đã có. Như vậy mỗi lần mình insert, xóa, delete 1 phần tử trong file thì chương trình sẽ tạo file mới và đè lên file cũ, ko chỉnh sửa trong file cũ. Mình hiểu như vậy có đúng code ko. Nếu đúng thì làm sao sửa lại theo kiểu thao tác chỉ trên 1 file, ko tạo file mới đè lên. Thanks!!!

Trịnh Minh Cường viết 01:18 ngày 01/10/2018

f = fopen(fileName, “wb”);

Cái này bạn sửa thành:
f = fopen(fileName, "a+"); thử xem tại lâu quá cũng không đụng tới C rồi.
a+: là mở file để update có thể dùng cho cả read và write

Tao Không Ngu. viết 01:25 ngày 01/10/2018

This post was flagged by the community and is temporarily hidden.

Dat viết 01:18 ngày 01/10/2018

Cách di chuyển con trỏ thì như thế nào bạn? Múa vài đường cho mình thông được hok?

Bài liên quan
0