Archived

This topic is now archived and is closed to further replies.

Nali

file I/O with fread() & fwrite()

Recommended Posts

How do I write multiple items into a single file.. for example: I would like to write a string array and an integer array into a file called "myfile.dat" I use this code: ---------------------------------------------------------- char myCharArray[10][8]; int myIntArray[10]; FILE *pFile; pFile = fopen("myfile.dat","r+b"); // write fwrite(&myCharArray,sizeof(myCharArray),2,file); fwrite(&myIntArray,sizeof(myIntArray),2,file); // read fread(&myCharArray,sizeof(myCharArray[10][8]),2,file); fread(&myIntArray,sizeof(myIntArray[10]),2,file); ---------------------------------------------------------- but it screwes up my values.. the arrays are a part in a class and are declared public for easy access while I test my class in a console app

Share this post


Link to post
Share on other sites
try this;

      
char myCharArray[10][8];
int myIntArray[10];

FILE *pFile;

pFile = fopen("myfile.dat","wb"); // for writing, use "wb"


// write

fwrite(myCharArray,sizeof(char),8*10,pFile); // check & before myCharArray, you shouldn't put it

fwrite(myIntArray,sizeof(int),10,pFile);

fclose(pFile); // i hope you were doing this before too

// re-open the file here

pFile = fopen("myfile.dat","r+b");

// read

fread(&myCharArray,sizeof(char),8*10,pFile);
fread(&myIntArray,sizeof(int),10,pFile);

fclose(pFile);


cheers

edits: i cannot typeeeee...
-----------
my quote is under construction

Edited by - mentat on February 21, 2002 9:44:47 AM

Edited by - mentat on February 21, 2002 9:46:09 AM

Share this post


Link to post
Share on other sites
Aha!! I now understand what the problem was!
I thought that the third parameter,fwrite(,,2,),was how many different items which should be written into the file.. I have 2.. but it was how many elements my arrays had..

I use the fclose() function but didn''t wrote it when I explained my problem.. my function doens''t look like that either but you understanded my code..thats good =)

Thanks Mentat!!!
I can now continue with my work..

Share this post


Link to post
Share on other sites