首页 > 技术文章 > C语言文件操作-按行读写文件

beautiful7 2020-11-02 19:03 原文

 1 //按行读写文件
 2 #define _CRT_SECURE_NO_WARNINGS
 3 #include<stdio.h>
 4 #include<stdlib.h>
 5 #include<string.h>
 6 
 7 //获取键盘输入,写入文件
 8 void Get_stdin_Write_File()
 9 {
10     FILE* fp;
11     char buf[4096];
12     fp = fopen("test2.txt", "w");
13     if (fp == NULL)
14     {
15         perror("Open file Error:");
16         return;
17     }
18     else
19     {
20         while (1)
21         {
22             fgets(buf, 4096, stdin);//需要注意的是这里用fgets读入会把\n也读进去
23             if (strcmp(buf, ":wq\n") == 0)
24             {
25                 printf("输入完毕\n");
26                 break;
27             }
28             else
29             {
30                 fputs(buf, fp);
31 
32             }
33         }
34     }
35     fclose(fp);
36     return;
37 }
38 int main()
39 {
40     Get_stdin_Write_File();
41     return 0;
42 }

 

推荐阅读