Page 167 - C-Language
P. 167

i++;
             }
         }


        The output will be:


         Word 1: This
         Word 2: is
         Word 3: just
         Word 4: a
         Word 5: test
         Word 6: file
         Word 7: to
         Word 8: be
         Word 9: used
         Word 10: by
         Word 11: fscanf()



        Read lines from a file


        The stdio.h header defines the fgets() function. This function reads a line from a stream and
        stores it in a specified string. The function stops reading text from the stream when either n - 1
        characters are read, the newline character ('\n') is read or the end of file (EOF) is reached.


         #include <stdio.h>
         #include <stdlib.h>
         #include <string.h>

         #define MAX_LINE_LENGTH 80

         int main(int argc, char **argv)
         {
             char *path;
             char line[MAX_LINE_LENGTH] = {0};
             unsigned int line_count = 0;

             if (argc < 1)
                 return EXIT_FAILURE;
             path = argv[1];

             /* Open file */
             FILE *file = fopen(path, "r");

             if (!file)
             {
                 perror(path);
                 return EXIT_FAILURE;
             }

             /* Get each line until there are none left */
             while (fgets(line, MAX_LINE_LENGTH, file))
             {
                 /* Print each line */
                 printf("line[%06d]: %s", ++line_count, line);

                 /* Add a trailing newline to lines that don't already have one */
                 if (line[strlen(line) - 1] != '\n')



        https://riptutorial.com/                                                                             143
   162   163   164   165   166   167   168   169   170   171   172