[英]trying read and write on the same code in c program
Help I'm trying to write the data in the file.帮助我正在尝试将数据写入文件中。 then, trying to read it back, but its not working.
然后,试图读回它,但它不起作用。
#include <stdio.h>
int main(void) {
FILE *fptr = fopen("try.txt", "r+");
char line[1000];
fprintf(fptr, "i have new number = 1425");
while (fgets(line, 1000, fptr)) {
printf("%s",line);
}
return 0;
}
You must use a positioning function such as rewind()
or fseek()
between read and write operations.您必须在读写操作之间使用定位 function 例如
rewind()
或fseek()
。
Beware that the update mode for streams is very confusing and error prone, you should avoid using it and structure your programs accordingly.请注意,流的更新模式非常混乱且容易出错,您应该避免使用它并相应地构建您的程序。
Incidentally, your program will fail to open try.txt if it does not already exist, but you do not check for fopen
failure so you will get undefined behavior in this case.顺便说一句,如果try.txt不存在,您的程序将无法打开它,但您不检查
fopen
失败,因此在这种情况下您将获得未定义的行为。
Here is a modified version:这是修改后的版本:
#include <stdio.h>
int main(void) {
char line[1000];
FILE *fptr = fopen("try.txt", "w+");
if (fptr != NULL) {
fprintf(fptr, "I have new number = 1425\n");
rewind(fptr);
while (fgets(line, sizeof line, fptr)) {
printf("%s", line);
}
fclose(fptr);
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.