c++循环读取多行文本文件

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

  自己写的代码

  #include <stdio.h>

  #include <stdlib.h>

  #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 <stdio.h>

  #include <stdlib.h>

  #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

猜你喜欢

转载自blog.csdn.net/outer_star/article/details/14523917