954,483 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

I/O array of integer

hi,

im trying to read and write an array of integer to/from a file. i use this to
write to a file:

fwrite(texel, sizeof(int), size, fp);


and this to write it:

(*out) = new int[size];
fread((*out), sizeof(int), size, fp);


but the data read from the same file is different. im not sure what happened but
from the real data, its a bunch of integer with differnece = 2 (even numbers)
but when i read it, its a sequence of number(1, 2, 3, 4). i think its halved or
something.

any idea why?

thanks in advance

jos_t_tarigan
Newbie Poster
2 posts since Aug 2010
Reputation Points: 10
Solved Threads: 0
 

maybe you are not opening the file in binary mode. This works ok for me

int main()
{
    int *parray = 0;
    int ay[] = {1,2,3,4,5,6,7,8,9,10};
    int size = sizeof(ay) / sizeof(ay[0]);
    FILE* fp = fopen("filename.dat","wb");
    fwrite(ay,sizeof(int), size,fp);
    fclose(fp);
    
    parray = new int[size];
    fp = fopen("filename.dat","rb");
    fread(parray, sizeof(int), size,fp);
    fclose(fp);
    for(int i = 0; i < size; i++)
        cout << parray[i] << '\n';
}
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: