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!!!
tại lâu quá cũng không đụng tới C rồi.
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?