vendredi 29 juillet 2016

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.

Aucun commentaire:

Enregistrer un commentaire