c 如何读取txt文件

2025-10-28 05:08:43

1、使用VS新建空工程,直接点击确定,如下所示。

c  如何读取txt文件

2、新建c文件,用于C语言编译器,输入main.c文件,如下所示。

c  如何读取txt文件

c  如何读取txt文件

3、参考代码:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#define MAX_LINE 1024

void ReadTxt(char* pFilePath)

{

char buf[MAX_LINE];  /*缓冲区*/

FILE *fp;            /*文件指针*/

int len;             /*行字符个数*/

if((fp = fopen(pFilePath,"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 ;

}

int main()

{

ReadTxt("D:\\test.txt");  //读取TXT文件函数

getchar();

return 0;

}

4、将上述参考代码,复制到main.c文件内,直接编译即可。

c  如何读取txt文件

5、编译完成后,运行exe程序,执行后显示console程序,如下所示。

c  如何读取txt文件

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢