简体   繁体   中英

Why in the given piece of code `fgetc()` function gave proper output whereas `fscanf()` failed to do so?

The following piece of code worked :

 #include<stdio.h>
    void main()
    {
        FILE *ip, *op ;
        char ch ;
        ip = fopen ( "read.txt", "r" ) ;
        op = fopen ( "out.txt", "a" );
        while ( 1 )
        {
            ch = fgetc ( ip ) ;   //used for getting character from file read.txt
            if ( ch == EOF )
                break ;
            fprintf ( op, "%c", ch ) ;
        }
            fclose ( ip ) ;
            fclose ( op );
    }

But the following code was not giving required output as fscanf() was used :

#include<stdio.h>
void main()
{
    FILE *fp, *op ;
    char ch ;
    fp = fopen ( "read.txt", "r" ) ;
    op = fopen ( "out.txt", "a" );
    while ( 1 )
    {
        ch = fscanf ( fp, "%c", &ch ) ;  //to read the characters from read.txt
        if ( ch == EOF )
            break ;
        fprintf ( op, "%c", ch ) ;
    }
        fclose ( fp ) ;
        fclose ( op );
}

I also don't understand how the variable ch was automatically taking up the next character.

The problem is that you're assigning the result of fscanf to ch :

    ch = fscanf ( fp, "%c", &ch ) ;  //to read the characters from read.txt
//  ^^^^^---- here
    if ( ch == EOF )
        break ;

So first fscanf reads a character into ch (if there is one), and then it returns, and its return value is writte to ch , overwriting the character. The return value of fscanf is "Number of receiving arguments successfully assigned, or EOF if read failure occurs before the first receiving argument was assigned." When when there's a character to read, you end up with ch being set to 1.

So:

if (fscanf ( fp, "%c", &ch ) != 1) {
    break;

or

if (fscanf ( fp, "%c", &ch ) == EOF) {
    break;

I also don't understand how the variable ch was automatically taking up the next character.

Note the &ch part of fscanf ( fp, "%c", &ch ) : That takes the address of the ch variable and passes that address into fscanf ; fscanf receives a pointer to ch . fscanf writes data to the memory that pointer points to, which is why it ends up in ch .

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