我正在学习如何在C语言中处理文件。到目前为止,我可以使用fopen + fprintf函数编写(创建)txt文件,但是我不了解读写参数的工作原理。
每当我使用a +,w +或r +时,我的程序只会写入信息,而不会读取信息。我必须关闭文件,然后以只读模式重新打开它。以下代码可以更好地说明:
此代码对我来说无效不起作用:
#include<stdio.h>
#include<stdlib.h>
int main(void){
FILE * myfile = nullptr;
myfile = fopen("./program.txt", "a+"); // I also tried w+ and r+
int num1 = 4;
int num2 = 0;
fprintf(myfile, "%d", num1);
fscanf(myfile, "%d", &num2); // the atribution does not occur
// num2 keeps previous value
printf("%d", num2);
fclose(myfile);
return (0);}
这很好:
#include<stdio.h>
#include<stdlib.h>
int main(void){
FILE * myfile = nullptr;
myfile = fopen("./program.txt", "w");
int num1 = 4;
int num2 = 0;
fprintf(myfile, "%d", num1);
fclose(myfile); //close the file!
myfile = fopen("./program.txt", "r"); // reopen as read only!
fscanf(myfile, "%d", &num2);
printf("%d", num2);
fclose(myfile);
return (0);}
是否有任何方法可以处理文件(读取和修改文件)而无需每次都关闭它?
答案 0 :(得分:3)
当您想回读刚写的内容时,必须将文件光标移回开始处(或您要开始读取的任何位置)。这是通过fseek
完成的。
#include<stdio.h>
#include<stdlib.h>
int main(void) {
FILE * myfile = NULL;
myfile = fopen("./program.txt", "a+"); // I also tried w+ and r+
int num1 = 4;
int num2 = 0;
fprintf(myfile, "%d", num1);
fseek(myfile, 0, SEEK_SET);
fscanf(myfile, "%d", &num2); // the atribution does not occur
// num2 keeps previous value
printf("%d", num2);
fclose(myfile);
}