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 }