Hi,

i have a problem here i am trying to write to a file through fwrite and read through fread functions.

it asks me to enter 5 values with no problem but when i trying to read from a file it prints 6 values, the 5th values prints twice what's wrong with the code ??

here is my code:

#include<stdio.h>

int main()
{
    int height,i=0;
    float avg=0;
    FILE *fp;

    if((fp = fopen("file1","w")) != NULL)
    {
        while(i<5)
        {
            printf("Enter Height of Student %d : ",i+1);
            scanf("%d",&height);
            fwrite(&height,2,1,fp);
            i++;            
        }
    }
    fclose(fp);

    printf("\n\n");
    if((fp = fopen("file1","r")) != NULL)
    {
        while(!feof(fp))
        {
            fread(&height,2,1,fp);
            printf("%d\n",height);
        }
    }

    fclose(fp);

return 0;
}
size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );

I will suggest you to use sizeof operator for second parameter in the fread function. although, it will work correctly for some cases, but it will be problematic if integer is of 4 bytes on any other machine. try to change that, may be it will work. hope it helps! thanks.

Edited 3 Years Ago by nitin1

Thanks for the reply nitin i tried everything you said but nothing works
if i enter 1,2,3,4,5. it prints out 1 2 3 4 5 5

printf("Enter Height of Student %d : ",i+1);
scanf("%d",&height);
fwrite(&height,2,1,fp);
i++;

your incrementing i twice in the same loop . i havent run your code yet , but i dont think thats how it should work.

my bad , my brain must had gone totally bonkers , i thought i+1 was incrementing i !!

Edited 3 Years Ago by somjit{}

see this
until the eof mark is set , the last entry will be repeatedly fetched . its better to use an array i feel , and in the while loop at the end , apply index < length of array condition.

Edited 3 Years Ago by somjit{}

I think this is better

if(fread(&height,sizeof(height),1,fp) > 0)
{
    printf("%d ",height);
}

Edited 3 Years Ago by Muhammad Waqar_1

This question has already been answered. Start a new discussion instead.