C++如何循环读取多行文件

原创|其它|编辑:郝浩|2010-02-21 13:17:55.000|阅读 2648 次

概述:C++如何循环读取多行文件?其实主要的思路就是每次调用fgets,文件指针都会跳到下一行。

# 界面/图表报表/文档/IDE等千款热门软控件火热销售中 >>

  其实主要的思路就是每次调用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); //应该释放空间
  }


标签:

本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@evget.com

文章转载自:网络转载

为你推荐

  • 推荐视频
  • 推荐活动
  • 推荐产品
  • 推荐文章
  • 慧都慧问
扫码咨询


添加微信 立即咨询

电话咨询

客服热线
023-68661681

TOP