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;
}

Recommended Answers

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 …

Jump to Post
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.

Jump to Post

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

Jump to Post

All 9 Replies

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.

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.

i++;
is for loop when i = 6 the loop terminates

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

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.

I think this is better

if(fread(&height,sizeof(height),1,fp) > 0)
{
    printf("%d ",height);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.