简体   繁体   中英

reading string from a file via stdin in c11

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.

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 .

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("%39s", 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM