I wrote this function to read a line from a file:
const char *readLine(FILE *file) {
if (file == NULL) {
printf(\"Error: file pointer is null.\"
A complete, fgets() solution:
#include
#include
#define MAX_LEN 256
int main(void)
{
FILE* fp;
fp = fopen("file.txt", "r");
if (fp == NULL) {
perror("Failed: ");
return 1;
}
char buffer[MAX_LEN];
// -1 to allow room for NULL terminator for really long string
while (fgets(buffer, MAX_LEN - 1, fp))
{
// Remove trailing newline
buffer[strcspn(buffer, "\n")] = 0;
printf("%s\n", buffer);
}
fclose(fp);
return 0;
}
Output:
First line of file
Second line of file
Third (and also last) line of file
Remember, if you want to read from Standard Input (rather than a file as in this case), then all you have to do is pass stdin
as the third parameter of fgets()
method, like this:
while(fgets(buffer, MAX_LEN - 1, stdin))
Appendix
Removing trailing newline character from fgets() input
how to detect a file is opened or not in c