如何编写和创建文件,如果文件存在则附加,然后显示所有字符串文件文本?我无法将内容附加到文件文本的末尾,然后显示所有字符串。感谢阅读!
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include<unistd.h>
int main(int argc, char** argv) {
char c, filename[100], content[100];
FILE *fptr;
printf("File name: ");
scanf("%s", filename);
printf("Enter content: ");
gets(content);
if ((fptr = fopen(filename, "r")) == NULL)
{
fptr = fopen(fptr, "w");
fprintf(fptr,"%s", content);
}
else{
fptr = fopen(fptr, "a");
fprintf(fptr,"%s", content);
}
c = fgetc(fptr);
while (c != EOF)
{
printf ("%c", c);
c = fgetc(fptr);
}
fclose(fptr);
return 0;
}
答案 0 :(得分:0)
如果您想打开一个文件进行阅读并附加到该文件,只需使用模式fopen
拨打a+
即可。
fptr = fopen(filename, "a+");
if (fptr == NULL)
{
// Handle not being able to open the file
}
如果文件不存在,它将创建它。阅读的位置将在文件的开头,但是你写的任何内容都将在最后。
答案 1 :(得分:0)
其他人在评论中提到了很多错误。我试着在评论中解释一下,仔细阅读。
int main(int argc, char** argv) {
char filename[100], content[100];
FILE *fptr;
printf("Enter content: \n");
fgets(content,sizeof(content),stdin); /*use fgets() instead of gets()*/
printf("File name: ");
scanf("%s", filename);
if ((fptr = fopen(filename, "r")) == NULL) {/*if doesn't exist */
fptr = fopen(filename, "w"); /*create it */
fprintf(fptr,"%s", content); /* and write it */
}
else{
/* it should be a+ if you want to read, as you are doing using fgetc() */
fptr = fopen(filename, "a+");/*if exist, write at end of file */
fprintf(fptr,"%s", content);/* write at end */
}
rewind(fptr);/* move the fptr to beginning to read further */
int c = 0; /* fgetc() returns integer */
while( (c = fgetc(fptr))!= EOF) {
printf ("%c\n", c);
}
fclose(fptr);
return 0;
}
使用fgets()
代替gets()
。阅读Why is the gets function so dangerous that it should not be used?