即使再次运行代码,我也想将数据存储在file.txt中。每当我运行代码时,它都会删除所有以前的数据。
#include <stdio.h>
#include <stdlib.h>
int main() {
char sentence[1000];
FILE *fptr = fopen("file.txt", "w");
if (fptr == NULL) {
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
fgets(sentence, sizeof(sentence), stdin);
fprintf(fptr, "%s", sentence);
fclose(fptr);
return 0;
}
以“附加”模式打开文件:
#include <stdio.h>
#include <stdlib.h>
int main() {
char sentence[1000];
FILE *fptr = fopen("file.txt", "a"); /* <===== changed from "w" to "a" */
if (fptr == NULL) {
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
fgets(sentence, sizeof(sentence), stdin);
fprintf(fptr, "%s", sentence);
fclose(fptr);
return 0;
}
现在将在文件末尾添加新数据。