0
点赞
收藏
分享

微信扫一扫

(每日一练c语言)写入字符串到文件txt,并追加字符

和谐幸福的人生 2022-02-01 阅读 104

写入字符串到文件

下面正确将"Hello,World!"写入文件,并再次打开追加写入"Hello,World!",最后一次打开并读取出来打印两行"Hello,World!"的代码是?

#include <stdio.h>

int main(int argc, char **args) {
  // 写入
  FILE *f1 = fopen("/tmp/hello.txt", "w+");
  fputs("Hello,World!\n", f1);
  fclose(f1);

  // 追加
  FILE *f2 = fopen("/tmp/hello.txt", "a+");
  fputs("Hello,World!\n", f1);
  fclose(f2);

  // 读取
  FILE *f3 = fopen("/tmp/hello.txt", "r+");
  char buff[1024];

  fgets(buff, 1024, f3);
  printf("%s", buff);

  fgets(buff, 1024, f3);
  printf("%s", buff);

  fclose(f3);

  return 0;
}
举报

相关推荐

0 条评论