Difference between scanf() and fgets()

There are multiple differences. Two crucial ones are: fgets() can read from any open file, but scanf() only reads standard input. fgets() reads ‘a line of text’ from a file; scanf() can be used for that but also handles conversions from string to built in numeric types. Many people will use fgets() to read a … Read more

Return value of fgets()

The documentation for fgets() does not say what you think it does: From my manpage fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the … Read more

How to prevent fgets blocks when file stream has no new data

In Linux (or any Unix-y OS), you can mark the underlying file descriptor used by popen() to be non-blocking. #include <fcntl.h> FILE *proc = popen(“tail -f /tmp/test.txt”, “r”); int fd = fileno(proc); int flags; flags = fcntl(fd, F_GETFL, 0); flags |= O_NONBLOCK; fcntl(fd, F_SETFL, flags); If there is no input available, fgets will return NULL … Read more

Reading from file using fgets

You need to check the return value of fgets. If a read has been successful, fgets returns the pointer to the buffer that you passed to it (i.e. string in your example). If the End-of-File is encountered and no characters have been read, fgets returns NULL. Try this: char string[100]; while(fgets(string, 100, fp)) { printf(“%s\n”, … Read more

How to read from stdin with fgets()?

here a concatenation solution: #include <stdio.h> #include <stdlib.h> #include <string.h> #define BUFFERSIZE 10 int main() { char *text = calloc(1,1), buffer[BUFFERSIZE]; printf(“Enter a message: \n”); while( fgets(buffer, BUFFERSIZE , stdin) ) /* break with ^D or ^Z */ { text = realloc( text, strlen(text)+1+strlen(buffer) ); if( !text ) … /* error handling */ strcat( text, … Read more