Home > Net >  reading string from a file via stdin in c11
reading string from a file via stdin in c11

Time:07-30

So I have a .txt file that I want to read via stdin in c11 program using scanf().

The file is essentially many lines made of one single string.

example:

hello
how
are
you

How can I know when the file is finished, I tried comparing a string with a string made only with eof character but the code loops in error.

Any advice is much appreciated.

CodePudding user response:

Linux manual says (RETURN section):

RETURN VALUE

   On success, these functions return the number of input items
   successfully matched and assigned; this can be fewer than
   provided for, or even zero, in the event of an early matching
   failure.

   The value EOF is returned if the end of input is reached before
   either the first successful conversion or a matching failure
   occurs.  EOF is also returned if a read error occurs, in which
   case the error indicator for the stream (see ferror(3)) is set,
   and errno is set to indicate the error.

So test if the return value of scanf equals to EOF.

CodePudding user response:

You can read the file redirected from standard input using scanf(), one word at time, testing for successful conversion, until no more words can be read from stdin.

Here is a simple example:

#include <stdio.h>

int main() {
    char word[40];
    int n = 0;

    while (scanf("9s", word) == 1) {
        printf("%d: %s\n",   n, word);
    }
    return 0;
}

Note that you must tell scanf() the maximum number of characters to store into the destination array before the null pointer. Otherwise, any longer word present in the input stream will cause undefined behavior, a flaw attackers can try and exploit using specially crafted input.

  • Related