How to use fgets to read a file line by line

前端 未结 3 1363
庸人自扰
庸人自扰 2021-01-25 04:21

I\'m new at programming so there are some basics and maybe common sense that I don\'t know. I have a question about how to use fgets right. Based on the explanation of fgets, it

3条回答
  •  闹比i
    闹比i (楼主)
    2021-01-25 04:59

    // hello.c
    //
    // Usage:
    //
    // gcc -Wall hello.c && ./a.out /tmp/somefile.txt
    
    #include      // for perror, ...
    #include       // for printf, ...
    #include      // for assert
    #include    // 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
    

提交回复
热议问题