How to use fgets to read a file line by line

别来无恙 提交于 2019-12-02 09:36:54
 #include <stdio.h>

 int main()
 {
    char str[150],str2[100][150];
    int i=0,j=0,value[100];
    FILE* fp;
    fp = fopen("file.txt", "r");
    while (fgets(str,150, fp)) {
        i++;
        printf("%3d: %s\n", i, str);
        /** if you want to split value and string*/
        sscanf(str,"%s %d",&str2[j],&value[j]);
        printf("%d %s\n",value[j],str2[j]);
        j++;
    }
    fclose(fp);
    return 0;
}
// hello.c
//
// Usage:
//
// gcc -Wall hello.c && ./a.out /tmp/somefile.txt

#include <stdlib.h>     // for perror, ...
#include <stdio.h>      // for printf, ...
#include <assert.h>     // for assert
#include <sys/time.h>   // for gettimeofday

static inline long long int nowUs () {
  long long int now;
  struct timeval timer_us;
  if (gettimeofday(&timer_us, NULL) == 0) {
    now = ((long long int) timer_us.tv_sec) * 1000000ll +
      (long long int) timer_us.tv_usec;
  }
  else now = -1ll;

  return now;
}

int main (const int argc, const char * argv[]) {
  assert(2 == argc);
  long long int started = nowUs();
  size_t count = 0;
  char msg[128], * fgets_rv;
  FILE * fp = fopen(argv[1], "r");

  while ((fgets_rv = fgets(msg, sizeof(msg), fp))) {
    assert(fgets_rv == msg);
    count++;
  }
  if (ferror(fp)) 
    perror(argv[1]);
  else if (feof(fp)) {
    printf("Read %zu lines of file '%s' in %lldµs\n", 
        count, argv[1], nowUs() - started);
  }
  else {
    printf("UNEXPECTED\n");
  }
  fclose(fp);
  return 0;
}

Sample output:

alec@mba ~/process/sandbox $ gcc -Wall hello.c && ./a.out /tmp/bigfile.t02
Read 100000 lines of file '/tmp/bigfile.t02' in 16521µs
fp = fopen("sample.txt", "r");
while (1) {
        if (fgets(line,150, fp) == NULL) break;
        i++;
        printf("%3d: %s", i, line);
}
printf("%d\n",i);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!