您的位置:首页 > 编程语言 > C语言/C++

c语言如何从txt文件读取数据

2017-05-24 21:37 465 查看
打开文件 fopen("需要打开的路径")

然后使用fgets函数读取行


#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: