Stefano
Stefano

Reputation: 37

Copying file text in C using getc() and putc() - binary code in the output file

I created a file called "text.txt" with a string inside and I want to copy that string in another file called "copiaqui.txt". But there's a problem. In the output file, I found this :

[CLICK][1].

Why the program doesn't copy the string correctly?

Code :

#include <stdio.h>
#include <stdlib.h>

void copiaFile(FILE *fi, FILE *fo);

int  main(void)
{
    FILE *fi = fopen("test.txt", "r");
    FILE *fo = fopen("copiaqui.txt","w");   

    if (fi == NULL)
    {
        printf("\nImpossibile aprire il file test.txt\n");
        exit(EXIT_FAILURE);
    } 

    if (fo == NULL)
    {
        printf("\nImpossibile aprire il file copiaqui.txt\n");  
        exit(EXIT_FAILURE);
    }

    copiaFile(fi, fo);

    fclose(fi);
    fclose(fo);
    return 0;
}

void copiaFile(FILE *fi, FILE *fo)
{
    int var;

    while((var = getc(fi) != EOF))
    {
        printf("\nCarattere acquisisto : %c", var);
        putc(var, fo);
    }


}

Upvotes: 0

Views: 664

Answers (1)

Bill - K5WL
Bill - K5WL

Reputation: 716

You have made a common mistake with this expression:

var = getc(fi) != EOF

What this does is assign the value of (getc(fi) != EOF) to var, because of something called operator precedence. The value is either true or false. What you intended to do is:

(var = getc(fi)) != EOF

Which will make var have the getc() value, then check that against EOF.

Upvotes: 4

Related Questions