C语言读取txt文件实例

本文主要总结用C语言来读txt文本的内容,具体的步骤如下所述。


1.1建一个.c源文件,复制如下代码。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE 1024
int main()
{
 char buf[MAX_LINE];  /*缓冲区*/
 FILE *fp;            /*文件指针*/
 int len;             /*行字符个数*/
 if((fp = fopen("test.txt","r")) == NULL)
 {
 perror("fail to read");
 exit (1) ;
 }
 while(fgets(buf,MAX_LINE,fp) != NULL)
 {
 len = strlen(buf);
 buf[len-1] = '\0';  /*去掉换行符*/
 printf("%s %d \n",buf,len - 1);
 }
  return 0;
}


1.2在.c源文件同目录下,新建一个名为test.txt的文本文件,在其中随意写入内容,比如我写入的内容为:

I an a string! 1234567



1.3在cygwin下,敲入如下指令进行编译,生成.exe可执行程序,如下图所示:

gcc write_txt.c -o write_txt.exe





1.4继续在cygwin下,敲入如下指令,执行.exe可执行程序,结果如下图所示:

./write_txt



由上面结果可知,该程序正确读出了test.txt文本文件的内容!



参考内容:

https://blog.csdn.net/baidu_29950065/article/details/51659913?yyue=a21bo.50862.201879(重点参考)

https://blog.csdn.net/u010925447/article/details/75046810

猜你喜欢

转载自blog.csdn.net/naibozhuan3744/article/details/80610476
今日推荐