Reputation: 45
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.
Upvotes: 1
Views: 89
Reputation: 1074694
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
.
Upvotes: 4