The following is a bare-bones code structure for reading from a file, line-by-line in C. It’s not difficult at all, but just in case you forgot – this should get you up and running in no time.
This will just read a file (file.txt) line by line and print it’s contents to stdout.
// include standard input / output header file #include <stdio.h> int main(void) { /* Define the filename: file.txt Alternatively, you can also define a filepath like: /usr/bin/filename.txt */ static const char filename[] = file.txt; /* 50 is the max line size */ char line[50]; FILE *file = fopen(filename, r); if (file == NULL) { perror(filename); return 1; } /* we read each line using fgets */ while (fgets(line, sizeof line, file) != NULL) { /* write each line from file to stdout */ fputs(line, stdout); } fclose(file); return 0; }
Also, if you would like to remove the newline (n) character from each line that is being read, you can use strchr() to search the buffer for a newline to remove it like:
/* remove newline n from each line */ if (fgets(buffer, sizeof buffer, stdin)) { char *c = strchr(buffer, 'n'); if (c) *c = 0; ... }
Recent Comments