Answers for "how to get a whole line from text file in c"

C
3

read file in c line by line

#include <stdio.h>

int main(int argc, char* argv[])
{
    char const* const fileName = argv[1]; /* should check that argc > 1 */
    FILE* file = fopen(fileName, "r"); /* should check the result */
    char line[256];

    while (fgets(line, sizeof(line), file)) {
        /* note that fgets don't strip the terminating \n, checking its
           presence would allow to handle lines longer that sizeof(line) */
        printf("%s", line); 
    }
    /* may check feof here to make a difference between eof and io failure -- network
       timeout for instance */

    fclose(file);

    return 0;
}
Posted by: Guest on May-03-2021
0

how to print the file content each line in c

1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 
 5 int main(void) {
 6     // ...
 7 
 8     // "Empty" the string
 9     line[0] = '\0';
10 
11     while(fgets(chunk, sizeof(chunk), fp) != NULL) {
12         // Resize the line buffer if necessary
13         size_t len_used = strlen(line);
14         size_t chunk_used = strlen(chunk);
15 
16         if(len - len_used < chunk_used) {
17             len *= 2;
18             if((line = realloc(line, len)) == NULL) {
19                 perror("Unable to reallocate memory for the line buffer.");
20                 free(line);
21                 exit(1);
22             }
23         }
24 
25         // Copy the chunk to the end of the line buffer
26         strncpy(line + len_used, chunk, len - len_used);
27         len_used += chunk_used;
28 
29         // Check if line contains '\n', if yes process the line of text
30         if(line[len_used - 1] == '\n') {
31             fputs(line, stdout);
32             fputs("|*\n", stdout);
33             // "Empty" the line buffer
34             line[0] = '\0';
35         }
36     }
37 
38     fclose(fp);
39     free(line);
40 
41     printf("\n\nMax line size: %zd\n", len);
42 }
Posted by: Guest on May-24-2021

Code answers related to "how to get a whole line from text file in c"

Code answers related to "C"

Browse Popular Code Answers by Language