在C wierd输出中写入和读取CSV文件

G. *_*ira 0 c csv printf

我是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);
Run Code Online (Sandbox Code Playgroud)

我不知道为什么输出错了:

el;ol
ie
Run Code Online (Sandbox Code Playgroud)

提前致谢

aba*_*les 5

因为您正在循环条件下读取一个字符(因此在打印时会打印出所有其他字符),并在打印时读取另一个字符.试试这个:

int ch;
while ((ch=getc(fp)) != EOF) {
    printf("%c", ch);
}
Run Code Online (Sandbox Code Playgroud)