c - 如何写入或附加文本文件的内容然后显示?

标签 c

如何编写和创建文件,如果文件存在则追加,然后显示所有字符串文件文本?我无法将内容附加到文件文本末尾,然后显示所有字符串。感谢您的阅读!

#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;
}

最佳答案

如果您想打开一个文件进行读取并向其追加内容,只需使用 a+ 模式调用一次 fopen 即可完成此操作。

fptr = fopen(filename, "a+");
if (fptr == NULL)
{
   // Handle not being able to open the file
}

如果文件不存在,它将创建它。读取的位置将位于文件的开头,但写入的任何内容都将位于文件的末尾。

关于c - 如何写入或附加文本文件的内容然后显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50138926/

相关文章:

c - fscanf() 陷入无限循环

c - mprotect 整个程序,运行危险代码

c - RLE 编码...怎么了?

c - 从指定行读取文件到另一行

c - 管道无法读取 Enter 键(C、Linux)

c - 在宏中使用三元运算符

c - 同时使用 Direct-IO 写入和页面缓存读取是否安全?

c - 在 C 中获取错误 "expected identifier or ' (' before ' {' token

c - 如何在 C 中返回指向结构体数组的指针?

c - 在 C 中异或问题