yalcin
yalcin

Reputation: 541

File Operations on C

I wrote dynamic array to file.(100 width)And I read it from file.

But I realised that I can't read all of elements that I malloc from memory.

My code example is below:

main()
{
    FILE *file;
     int *numbers;
     int *numbers2;

     numbers = (int *)malloc(100*sizeof(int));
     numbers2 = (int *)malloc(100*sizeof(int)); 


    int i,j,tane;

    file=fopen("numbers.txt","w++");

    for(i=0;i<100;i++)
    { numbers[i]=i;}

    if(file==NULL)
    {printf("Error:File cannot open \n");
     return 1;
    }


    else {
          fwrite(numbers,4,100,file);

         }
    rewind(file);

    printf("Numbers read from file:\n");
    tane=fread(numbers2,4,100,file);
    for(i=0;i<tane;i++)
    { printf("%d ",numbers2[i]);}


    fclose(file);
    getch();
}

I see 0-25 elements that is printed by C . I can't understand that all of the elements doesn't print.( 0 to 100)

Could you help me please?

Best Regards...

Upvotes: 0

Views: 160

Answers (3)

pmg
pmg

Reputation: 108968

I guess sizeof (int) in your implementation is not 4.

I'm pretty sure it is sizeof (int) though. Try using sizeof (int) instead of magic constants. Even better would be to use the object itself as operand to sizeof ...

fwrite(numbers, sizeof *numbers, 100, file);
/*     also get rid of the MAGIC 100      */

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272457

You are opening your file in text mode, but you are writing binary data. Try fopen("numbers.txt", "wb+") instead.

Upvotes: 2

Cloudson
Cloudson

Reputation: 65

Fread function returns the numbers of line reads and not number of characters ok? http://www.cplusplus.com/reference/clibrary/cstdio/fread/

Upvotes: -1

Related Questions