c语言循环中怎样读取多行,c++循环读取多行文本文件

其实主要的思路就是每次调用fgets,文件指针都会跳到下一行。

自己写的代码

#include

#include

#define Line 1024

int main()

{

//读取多行文件,存多行文件

FILE *fp;

char filename[20];

printf("Please enter the file name\n");

gets(filename);

fp = fopen(filename,"r");

if(fp==NULL)

{

printf("File Open Error");

return 4;

}

char *buf;

buf = (char *)malloc(Line*sizeof(char));

char *p;

while(p = fgets(buf,Line,fp))

{

printf("%s",p);

//原来用puts,它还给你多打了一个换行符

}

free(buf);

fclose(fp);

return 0;

}

下面是抄别人的代码

#include

#include

#define line 1024

//fgets函数的返回值为指针,指向读进来的东西,如果读到没有了,就是0000000

char * readdata(FILE *fp, char *buf)

{

return fgets(buf,line, fp);//读取一行到buf         line 的默认值为1k

}

void someprocess(char *buf)

{

printf("%s", buf);//这里的操作你自己定义

}

void main()

{

FILE *fp;

char *buf, filename[20], *p;

printf("input file name:");

gets(filename);

if ((fp=fopen(filename, "r"))==NULL)

{

printf("open file error!!\n");

return;

}

buf=(char*)malloc(line*sizeof(char));     // buf用来存放读进来的字符串

while(1)

{

p=readdata(fp, buf);//每次调用文件指针fp会自动后移一行 readdata是一个函数

if(!p)//文件读取结束则跳出循环

break;

someprocess(buf);

}

free(buf);    //应该释放空间

}

摘自:http://c.chinaitlab.com/ccjq/802437.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值