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...)
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.


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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

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…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
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.

707 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now