我正在尝试将表数据写入 C 中的文件,我只想在一次输入后文件的第一行保持不变!我怎样才能做到这一点 ?预先感谢
我尝试了很多方法,但似乎没有一个适合我想要的。
这是我的代码
ỉnt main(){
FILE *fptr;
fptr = fopen("text.txt", "w");
if(strcmp(fgets("123", 1, fptr),"123")==0){
fclose(fptr);
}
else{
fprintf(fptr, "123");
fclose(fptr);
}
}
这里有一些问题:
<stdio.h>
和 <string.h>
"r"
而不是 "w"
,这是修改后的版本:
#include <stdio.h>
#include <string.h>
ỉnt main() {
FILE *fptr = fopen("text.txt", "r");
if (fptr) {
char buf[80];
if (fgets(buf, sizeof buf, fptr)) {
if (strcmp(buf, "123\n") == 0) {
printf("file contains 123\n");
} else {
printf("file does not contain 123: %s\n", buf);
}
} else {
printf("file is empty\n");
}
fclose(fptr);
} else {
printf("cannot open file %s\n", "text.txt");
}
return 0;
}