[英]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. 我是C语言的新手,我正在尝试将数据保存到.csv并在一个非常简单的程序中读取相同的数据。
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 提前致谢
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);
}
Here: 这里:
while (getc(fp) != EOF) {
printf("%c", getc(fp));
}
You are calling getc()
twice every time through the loop, but only printing one character. 您每次在循环中都两次调用getc()
,但仅输出一个字符。 So you get half te hrces rm te fl n ls h ohr hl. 这样您就可以节省一半的时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.