简体   繁体   English

fscanf什么都不读

[英]fscanf doesn't read anything

i am trying to read integers from a file and fscanf doesn't work well with this code. 我正在尝试从文件中读取整数,而fscanf不适用于此代码。

fp=fopen("record.dat","r");
if(fp==NULL)
{
    printf("Another reading error");
}
else
{
    printf("\nstarting to read\n");
    i=0;
    while(i<10)
    {
        if(fscanf(fp,"%d",&temp)>0)
        printf("%d\n",temp);
        i++;
    }
    fclose(fp);
}

the file contains 10 numbers which are delimited by a new line character. 该文件包含10个以换行符分隔的数字。 This code doesn't produce or print anything. 此代码不会产生或打印任何内容。 What is the problem with the code and pls help me with it. 代码有什么问题,请帮我解决。

EDIT the access mode as w+ or r isn't giving me a correct expected answer. 编辑访问模式,因为w +r没有给我正确的预期答案。

You are opening the file as a writable file instead of readable. 您正在将文件作为可写文件而不是可读文件打开。

You must change "w+" to "r" 您必须将"w+"更改为"r"

w+ The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.

"w+" actually opens file for reading and writing. 实际上, "w+"会打开文件进行读取和写入。 However, file is truncated to 0 length. 但是,文件被截断为0长度。
That might be the cause of printing blank lines. 这可能是打印空白行的原因。
Try "r+" (opens the file for reading and writing, without truncation) or "r" . 尝试使用"r+" (打开文件以进行读取和写入,不被截断)或"r"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM