Programming Tips - C/C++ read a line from a text file?

Date: 2018apr26 Language: C/C++ Level: beginner 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 = strchr(buf, '\n')) != NULL) *p = '\0'; // Remove newline return true; } void ExampleUse() { FILE *f; char buf[5 * 1024]; f = fopen("info.txt", "rt"); for(;;) { if (!ReadLine(f, buf, sizeof(buf))) break; printf("line=%s\n", buf); } fclose(f); }