Link to home
Start Free TrialLog in
Avatar of xenia27
xenia27Flag for Taiwan, Province of China

asked on

fwrite problem

Hi,

I got this problem...I use fwrite to write some structs into my files and sometimes it works perfectly but sometimes it didn't.
Here are my codes..

typedef struct _AStruct
{
      DataA myFiles[100];
      int SilbingIndex[100];
      int OtherIndex[60];
} AStruct;

typdef struct _DataA
{
    int index;
    UCHAR  Name[Name_Len];
    DataB   DataBuf[100];
} DataA

typdef struct _DataB
{
   char   DataBuffer[100];
   char   DataBuffer2[100];
} DataB


int  WriteFiles()
{
      int ret;
      DataFile = fopen(lpCurrentDataFilePath, "wb");

      EnterCriticalSection(lpcs_CNum);
      ret = fwrite(&ATree.myFiles, sizeof(DataA), 100, DataFile); <-- correct me if I'm wrong...it will return 100 if fwrite works fine, right?  but sometimes, it will return 99.  And I use "GetLastError", and it return 0...

      ret = fwrite(&ATree.SilbingIndex, sizeof(int), 100, DataFile);
                ret = fwrite(&ATree.OtherIndex, sizeof(int), 60, DataFile);
      ret = fclose(CSFile);  <-- this will return -1 if the first fwrite returns 99.

      return ret;
}

What's wrong with my codes?  Sometimes it works fine but sometimes it doesn't.  What should I do??
Avatar of Axter
Axter
Flag of United States of America image

ret = fwrite(&ATree.myFiles, sizeof(DataA), 100, DataFile);

This line has the wrong sizeof variable.
Try this instead:
ret = fwrite(&ATree.myFiles, 1, sizeof(ATree.myFiles), DataFile);
fwrite has the following parameters:
size_t fwrite( const void *buffer, size_t size, size_t count, FILE *stream );

Parameters
buffer
Pointer to data to be written

size
Item size in bytes

count
Maximum number of items to be written

stream
Pointer to FILE structure

So really your function should read like this:
ret = fwrite(&ATree.myFiles, sizeof(ATree.myFiles), 1, DataFile);

However, it will work both ways.  I myself always use 1 for one of the parameters, and then use the other parameter for the total size of the buffer.
>>ret = fclose(CSFile);  <-- this will return -1 if the first fwrite returns 99.

Using CSFile will give you an error since it's not the variable used to open the file.

Should be Datafile

ret = fclose(Datafile);  
SOLUTION
Avatar of Axter
Axter
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of xenia27

ASKER

Can I write this??

ret = fwrite(&ATree, sizeof(AStrue), 1, DataFile);
ATree is a poitner.

will this work?
Avatar of xenia27

ASKER

Another question, I use "fwrite(&ATree, sizeof(AStruct), 1, DataFile)", and why there is some information missed???
Hi Axter,
> By using sizeof() you're letting the compiler do the work for you.
Exactly - when fwrite returns only a partial write of the array (say, 99 of 100 elements), it's an error condition anyway. So write the entire array as one chunk. Or even better, write the whole ATree as a single piece. It's faster, it's more obvious what you're doing in the code, and it's less error-prone.

Cheers,
Stefan
xenia27,
> Another question, I use "fwrite(&ATree, sizeof(AStruct), 1, DataFile)",
> and why there is some information missed???

Which information is missed? It should be fine. But better write
fwrite(&ATree, sizeof(ATree), 1, DataFile)

That makes is more obvious that you're writing with both correct address and size.

Stefan
Avatar of xenia27

ASKER

OK...I got bool type in AStruct...

and now I'm using fwrite(ATree, sizeof(ATree), 1, DataFile);
and nothing is written into the file I want...@@...what's wrong?
>>fwrite(&ATree, sizeof(ATree), 1, DataFile)

Why do u require &ATree if ATree is a pointer
Also, sizeof ( ATree ) wont do if ATree is  a pointer
U should use

sizeof(AStruct)

Just
fwrite(ATree, sizeof(AStruct), 1, DataFile)
would do

HTH

Amit
Avatar of xenia27

ASKER

OK...I got something in my file but the BOOL part didn't written into my file..@@
Avatar of xenia27

ASKER

Sorry...one mistake...the one didn't written into the file is a UINT type...@@
Since u are writing the file in Binary mode, u won't be able to see the data using external editors

You will have to read back using fread() to get the data

The code works for me

Amit
Avatar of xenia27

ASKER

OK...I'm using VC to write my codes...and I set breakpoint around "fread" and try to see what did I write and there is nothing read....

fread(ATree, sizeof(AStruct), 1, DataFile);
and my fwrite
fwrite(ATree, sizeof(AStruct), 1, DataFile);      
Go thru this code
Since u are opening the file in "wb" mode, u can just write to the file
So, either close and file & reopen it in "rb" mode OR instead of opening the file in "wb" mode, open it in "rb+" i.e. Read + Write mode




struct data {
      bool b ;
      int  i ;
} ;

int main(int argc, char* argv[])
{
      data d ;
      d.i = 10 ;
      d.b = true ;
      
      FILE *fp = fopen ( "c:\\data.txt", "wb" ) ;
      fwrite ( &d, sizeof ( data ), 1, fp ) ;
      fclose ( fp ) ;
      
       data d1 ;      
      fp = fopen ( "c:\\data.txt", "rb" ) ;
      fread ( &d1, sizeof ( data ), 1, fp ) ;
      fclose ( fp ) ;
      
      cout << d1.i <<endl ;
      cout << d1.b ;
      system("pause");
      return 0;
}
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Here is the help for fopen function and different opening modes



Function: FILE * fopen (const char *filename, const char *opentype)

The fopen function opens a stream for I/O to the file filename, and returns a pointer to the stream.

The opentype argument is a string that controls how the file is opened and specifies attributes of the resulting stream.  It must begin with one of the following sequences of characters:

r

Open an existing file for reading only.


w

Open the file for writing only.  If the file already exists, it is truncated to zero length.  Otherwise a new file is created.


a

Open a file for append access; that is, writing at the end of file only.  If the file already exists, its initial contents are unchanged and output to the stream is appended to the end of the file.  Otherwise, a new, empty file is created.


r+

Open an existing file for both reading and writing.  The initial contents of the file are unchanged and the initial file position is at the beginning of the file.


w+

Open a file for both reading and writing.  If the file already exists, it is truncated to zero length.  Otherwise, a new file is created.


a+

Open or create file for both reading and appending.  If the file exists, its initial contents are unchanged.  Otherwise, a new file is created.  The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file.

HTH

Amit
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of xenia27

ASKER

I use another program to read the data...most of time, it works...but sometimes there is no data written in the file...still trying to figure out how would that happen.  @@  Is there anything happened will cause this result?  Any idea???
The only possible reasons are:
1. The reading and writing are happening with different data types/structures.

You can try one thing.
Comment out all other operations other than write to the file.
Similerly in the program which you read, comment out everything else other than read.
Now you can clearly see what is happening.
If it is not a huge code, you can post both read and write routines so that we can also analyze.....

-ssnkumar
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ssnkumar,
> how can you use fread() on this stream which is open for writing!?
On many systems you can.

Stefan
Avatar of xenia27

ASKER

OK...thanks for all the info...I follow all the steps but something is still wrong...I guess it's not the problem I thought it was...anyway, thanks for the info...they are helpful!!