G. Oliveira G. Oliveira - 10 months ago 53
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");
fp = fopen("file.csv", "r");
while (getc(fp) != EOF) {
printf("%c", getc(fp));


I don't know why the output is wrong:


Thanks in advance

Answer Source

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);