4
char c, cp;

FILE *input_file, *output_file;

input_file = fopen("d:\\input.txt","r");
output_file = fopen("d:\\output.txt", "w");

if(input_file==NULL){
    printf("cannot open the input.txt file.");
    exit(0);
}

if(output_file == NULL){
    printf("cannot open the output.txt file.");
    exit(0);
}

cp = fgetc(input_file);
while(cp!=EOF){
    fputc(cp,output_file);
    cp=fgetc(input_file);
}

c = fgetc(output_file);
while(c!=EOF){
    printf("%c",c);
    c=fgetc(output_file);
}

fclose(input_file);
fclose(output_file);
getch();

This is the code that I used while copying a text file. In the input.txt file I have written "Hello how are you".

After executing the code, the text "Hello how are you" is copied to the output.txt file but there are more than a hundred spaces after the copied text. After the code below the program is not working:

cp = fgetc(input_file);
while(cp!=EOF){
    fputc(cp,output_file);
    cp=fgetc(input_file);
}

Code below the above code is not working. What is happening? Please explain in detail. I am a beginner in C.

Boann
  • 48,794
  • 16
  • 117
  • 146
Nilmani Gautam
  • 157
  • 1
  • 11

2 Answers2

4

You must define c and cp as int not as char. EOF is defined as an integer value which is distinguishable from any char which may e.g. be read by fgetc(), which returns a value in the unsigned char range or EOF, not necessarily a value in the char range. (credits to @chux).

So while( cp != EOF ) might not become true if cp is a char.

And for the second issue: if you want to read what you have written you must

  1. open output.tx with mode "w+". "w" only permits writing, "w+" allows reading too but like "w" creates the file if it doesn't exist and truncates it if it does. See the man page for further options and details.
  2. call rewind(output_file) or fseek(output_file, 0, SEEK_SET) between reading and writing.
Ingo Leonhardt
  • 9,435
  • 2
  • 24
  • 33
0

you must close your output file to commit changes and be able to read a second time:

cp = fgetc(input_file);
while(cp!=EOF){
    fputc(cp,output_file);
    cp=fgetc(input_file);
}

fclose(output_file);
// .....        
c = fgetc(output_file);
Landstalker
  • 1,368
  • 8
  • 9