我试图在txt文件中保留一个conter,我编写了一个函数,当我调用函数时,函数应该读取txt之后,它应该递增并写入文件。
在我的txt(" test.txt")中只有一个字符。它是" 0"。
代码在这里:
void readAndwrite(){
int total = 23;
FILE *fread, *fwrite;
fread = fopen("test.txt", "r");
fwrite = fopen("test.txt","w");
fscanf(fread,"%d",&total);
fclose(fread);
++total;
fprintf(fwrite ,"%d",total);
fclose(fwrite);
}
int main(int argc, char const *argv[])
{
readAndwrite();
readAndwrite();
readAndwrite();
readAndwrite();
readAndwrite();
readAndwrite();
return 0;
}
为什么这不起作用?
答案 0 :(得分:0)
你可以打开两次但不能同时打开,因为“w”标志会破坏内容,所以:
void readAndwrite(){
int total = 23;
FILE *f;
f = fopen("test.txt", "r");
if(!f) {
perror("File opening failed");
}
else{
fscanf(f,"%d",&total);
fclose(f);
printf("%d\n", total);
++total;
f = fopen("test.txt","w");
fprintf(f ,"%d",total);
fclose(f);
}
}
如果您想同时读/写,请查看doc和“w +”标记