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...)
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.


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

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
GUI: DIalog Stacking and Popping in MS C++ 4 74
sorting efficency of sorting algorithm 30 112
C++ mouse_event mouse look 7 82
DCT of  2D array using fftw in c++ 9 38
Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
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 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.

786 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