从文件中读取每个字符

时间:2018-11-20 12:39:07

标签: c

我想阅读文本文件中的每个元素,包括换行和空格。这是我的代码

void test3()
{
    char a;
    FILE *csv;
    csv=fopen64("C:\\Users\\Md. Akash\\Desktop\\csv\\Book1.csv","r");
    int i;
    for(i=0;;i++)
    {
        if(fgetc(csv)==EOF)
            break;
        a=fgetc(csv);
        printf("%c",a);
    }
}

enter image description here

此代码跳过一个字符。

2 个答案:

答案 0 :(得分:1)

尝试将 for循环替换为以下内容:

/*
 Note:
 a = fgetc(csv) returns a character from the file pointed to by **csv** o returns **EOF** if the End Of File is reached.

 Therefore, it is probably a good idea to read every character from the file until the EOF is reached.

 The following **while** loop demonstrate just that.
*/
while((a =fgetc(csv)) != EOF){
     printf("%c", a)
}

答案 1 :(得分:1)

您在fgetc循环的每次迭代中两次调用for。而且您不会打印第一次获得的内容。

更改:

if(fgetc(csv)==EOF)
    break;
a=fgetc(csv);
printf("%c",a);

收件人:

if((a = fgetc(csv))==EOF)
    break;        
printf("%c",a);

注意:fgetc返回一个int。因此,a应该定义为int

相关问题