开发者

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 开发者_StackOverflow中文版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...


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


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      */


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜