Mani
Mani

Reputation: 1374

fscanf doesn't read anything

i am trying to read integers from a file and fscanf doesn't work well with this code.

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. 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.

Upvotes: 1

Views: 842

Answers (2)

Devolus
Devolus

Reputation: 22074

You are opening the file as a writable file instead of readable.

You must change "w+" to "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.

Upvotes: 3

mohit
mohit

Reputation: 6044

"w+" actually opens file for reading and writing. However, file is truncated to 0 length.
That might be the cause of printing blank lines.
Try "r+" (opens the file for reading and writing, without truncation) or "r".

Upvotes: 2

Related Questions