Write a struct to disk using WriteFile API

Posted on 1998-11-29
Last Modified: 2008-03-10
I am stuck trying to write a struct on disk using the WriteFile API function. The function works for dumping simple strings on disk by not a struct.


struct Record{
  CHAR cName[30];
  CHAR cZip[10];

void main(){
   DWORD dwBytes;
   BOOL bResult;
   bResult = WriteFile(hFile1, myRecord, sizeof(myRecord), &dwBytes, NULL);

Is there other way to accomplish this task?
Question by:misha051797
  • 4
  • 2
LVL 86

Accepted Solution

jkr earned 50 total points
ID: 1178819
Well, that's already the right way. But you'd better use the address of myRecord, e.g. '&myRecord' in order to get it working. The difference is, when you e.g. declare
char acMyArray[ 100];
'acMyArray' is already a pointer ro the first byte od 'acMyArray', whereas
'myRecord' in the example above is the record 'by value'. So the line should read
   bResult = WriteFile(hFile1, &myRecord, sizeof(struct Record), &dwBytes, NULL);


Author Comment

ID: 1178820
jkr thank you. i guess the proposed method should work. does the readfile API accepts the address as a second paprameter as well?

Here is what I have in mind:

struct Record{
      CHAR cName[30];
      CHAR cCity[10];

int main(){

      Record myRecord;

      DWORD dwBytes;
      BOOL bResult;
      cout << "Enter your name: ";
      cin >> myRecord.cName;
      cout << "Enter your city: ";
      cin >> myRecord.cCity;
    bResult = WriteFile(hFile1, &myRecord, sizeof(myRecord), &dwBytes, NULL);

bResult = ReadFile(hFile1, &myRecord, sizeof(myRecord), &dwBytes, NULL);

// Now after i read the data back in is it automatically placed in the appropriate structure data elements (cName and cCity)?
Can i use following to retrieve the cName?:

      cout << myRecord.cName;


      return TRUE;
Thank you.
LVL 86

Expert Comment

ID: 1178821
No - if you decide to write the data using 'WriteFile()' (which writes it in binary form!), you'll have to use 'ReadFile()' to retrieve it (BTW: What you're actually doing is called 'fixed record length' storage). So, if you use 'ReadFile()', the data will be stored in the appropriate fields of the structure. (BTW: The 2nd parameter is declared as a 'void*', so you can pass in _anything_ - if it is not a valid memory buffer, the result is - as you have experienced - inpredictable...)
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Author Comment

ID: 1178822
So in this case my program should work. Right? As you can see I did use WriteFile() finction. But when I read data into myRecord struct I get garbage. What is wrong with the example above?
Thank you.
LVL 86

Expert Comment

ID: 1178823
Well, 'sizeof(myRecord)' seems a bit unusual - i assume if you examine the contents of 'dwBytes', it'll already be different from 40. You'd better use 'sizeof(struct Record)' as i stated above. 'sizeof(<instance>)' usually is used for arrays...
LVL 11

Expert Comment

ID: 1178824
The problem is the file pointer.  At the end of the WriteFile operation, the file pointer points to *beyond* the written data.  And that's where you read from.

You should use SetFilePointer() to reposition the file pointer.

From the docs:

The WriteFile function writes data to a file and is designed for both synchronous and asynchronous operation. The function starts writing data to the file at the position indicated by the file pointer. After the write operation has been completed, the file pointer is adjusted by the number of bytes actually written, except when the file is opened with FILE_FLAG_OVERLAPPED. If the file handle was created for overlapped input and output (I/O), the application must adjust the position of the file pointer after the write operation is finished.

The ReadFile function reads data from a file, starting at the position indicated by the file pointer. After the read operation has been completed, the file pointer is adjusted by the number of bytes actually read, unless the file handle is created with the overlapped attribute. If the file handle is created for overlapped input and output (I/O), the application must adjust the position of the file pointer after the read operation.

LVL 86

Expert Comment

ID: 1178825
Well, misha - i assume you already closed the file before reading from it, haven't you? If not, alexo is right and you should use 'SetFilePointer( hFile1, 0, NULL, FILE_BEGIN);' to reposition it to the start of the file...

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

756 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question