How do I process a text file in C by chunks of lines?

后端 未结 3 1408
滥情空心
滥情空心 2021-01-21 12:01

I\'m writing a program in C that processes a text file and keeps track of each unique word (by using a struct that has a char array for the word and a count for its number of oc

3条回答
  •  無奈伤痛
    2021-01-21 12:48

    How about getline() ? Here an example from the manpage http://man7.org/linux/man-pages/man3/getline.3.html

       #define _GNU_SOURCE
       #include 
       #include 
    
       int
       main(void)
       {
           FILE *stream;
           char *line = NULL;
           size_t len = 0;
           ssize_t read;
    
           stream = fopen("/etc/motd", "r");
           if (stream == NULL)
               exit(EXIT_FAILURE);
    
           while ((read = getline(&line, &len, stream)) != -1) {
               printf("Retrieved line of length %zu :\n", read);
               printf("%s", line);
           }
    
           free(line);
           fclose(stream);
           exit(EXIT_SUCCESS);
       }
    

提交回复
热议问题