Question

I'm attempting to use the getc() function to copy the contents of one file into another. But I'm making an unknown logical error because the output of the following program is a bunch of garbage.

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

int main()
{
    FILE *f; 
    FILE *write;
    f = fopen("nums.csv","r");
    write = fopen("numsWrite.dat","w");

    char tempChar;

    int i;
    for(i = 0; (tempChar = getc(f)) != EOF; i++)
    {
        tempChar = getc(f);
        fprintf(write,"%c",tempChar);
    }
    fprintf(write,"\n");

    fclose(f);
    fclose(write);

    return 0;
}

content of nums.csv is:

1256,2548,35151,15,56,38

program returns:

2624,55,55,8
Was it helpful?

Solution

There are several problems with your code.

int main() should be int main(void); this is a minor issue that almost certainly won't hurt anything, but the latter is more correct.

You don't check whether the fopen() calls succeed.

You're using i to count the characters you read, but you never do anything with its value.

The getc() function returns a result of type int, so you should definitely make tempChar an int. The reason for this is that it can return either a valid character value (which will fit in a char object) or the value EOF which is typically -1. By storing the result of getc() in a char object, either you'll never see EOF (if plain char is unsigned), or you won't be able to distinguish EOF from a valid input character.

In a comment on Razvan's answer, you said you changed the test to tempChar != EOF. Apart from the problem I explained above, on the first iteration of the loop tempChar has not been initialized, and the result of the comparison is unpredictable.

The conventional way to write an input loop using getc() is:

int c;
while ((c = getc(f)) != EOF) {
    /* do something with c */
}

As a matter of style, write is not a very good name for a FILE*. For one thing, there's a function of that name (defined by POSIX, not by C, but it's still potentially confusing). You might call the FILE* objects in and out instead.

OTHER TIPS

You call getc two times: once in the for condition and once in the for body. Delete this line: tempChar = getc(f); and try again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top