Programming Tips - C/C++: Read a line from a text file

Date: 2018apr26 Update: 2026oct2 Language: C/C++ Q. C/C++: Read a line from a text file A. fgets() will read a line but it leaves the newline at the end which you usually don't want. So here a function which does it better.
#include <stdio.h> #include <string.h> bool ReadLine(FILE *f, char *buf, const size_t size) { char *p; buf[0] = '\0'; if (fgets(buf, size, f) == NULL) return false; if ((p = strrchr(buf, '\n')) != NULL) *p = '\0'; // Remove newline if ((p = strrchr(buf, '\r')) != NULL) *p = '\0'; // Remove carriage return (Windows) return true; }
Full Example Use:
#include <stdio.h> #include <string.h> // (Place ReadLine() from above here) int main() { FILE *f; char buf[5 * 1024]; if ((f = fopen("info.txt", "rt")) == NULL) { fprintf(stderr, "Could not open file\n"); return 1; } for(;;) { if (!ReadLine(f, buf, sizeof(buf))) break; printf("line=%s\n", buf); } fclose(f); }
Output:
line=line one line=line two line=line three