我需要构建一个读取每个记录的程序,并根据该记录信息来更新同一文件上的其他一些记录。为此,我正在考虑采用这种方法:
int main(int argc, char *argv[]) {
FILE *my_file;
int files_read;
struct my_struct an_struct;
my_file = fopen("myfile.dat", "rb");
files_read = fread(&an_struct, sizeof(struct my_struct), 1, my_file);
printf("main->files_read: %d \n", files_read); //This prints one
while (files_read == 1) {
do_update();
files_read = fread(&an_struct, sizeof(struct my_struct), 1, my_file);
printf("main->files_read: %d \n", files_read); //This prints one
}
fclose(archivo_paises);
return 0;
}
在main函数中,我正在读取文件的内容,每次调用时,都会read
得到一个响应,直到到达文件末尾。问题出在do_update
函数中:
void do_update() {
FILE *my_file;
int files_read;
struct my_struct an_struct;
struct my_struct another_struct;
my_files = fopen("myfile.dat", "wb+"); //Using rb+ solves it
files_read = fread(&an_struct, sizeof(struct my_struct), 1, my_file);
printf("do_update->files_read: %d \n", files_read);
//This printed zero!. Prints one using rb+
while (files_read == 1) { //This never gets executed. Unless you use rb+
if(something){
fwrite(&another_struct, sizeof(struct my_struct), 1, my_file);
// Using rb+, this returns zero and didn't update
}
files_read = fread(&an_struct, sizeof(struct my_struct), 1, my_file);
printf("do_update->files_read: %d \n", files_read);
}
fclose(my_file);
}
发生的情况是该files_read
变量在read
调用后获得的值为零,因此永远不会执行更新文件的逻辑。
为什么read
打开的文件时返回零wb+
?
更新:使用rb+
作为文件模式do_update()
的作品,但现在的调用fwrite()
总是返回零,并没有更新文件。是与模式有关吗?
fwrite
正在将文件中的位置移动到文件末尾。该fread
再没有什么阅读。
使用fgetpos
将文件保存位置之前fwrite
,和fsetpos
设置后的位置后面fwrite
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句