G. Oliveira G. Oliveira - 13 days ago 5
C Question

Writing and reading CSV file in C wierd output

I'm new to C language and I'm trying to save data to a .csv and read the same data in a very simple program.

char c;

FILE *fp;
fp = fopen("file.csv", "w+");
fprintf(fp, "Hello;World\nLine");
fclose(fp);
fp = fopen("file.csv", "r");
while (getc(fp) != EOF) {
printf("%c", getc(fp));
}

fclose(fp);


I don't know why the output is wrong:

el;ol
ie


Thanks in advance

Answer

Because you are reading a character in the loop condition (so it prints out every other one when printing), and reading another one when printing it out. Try this:

int ch;
while ((ch=getc(fp)) != EOF) {
    printf("%c", ch);
}
Comments