Solved

Write a struct to disk using WriteFile API

Posted on 1998-11-29
7
786 Views
Last Modified: 2008-03-10
Greetings,
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.

Example:

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

void main(){
   DWORD dwBytes;
   BOOL bResult;
   HANDLE hFile1 = CreateFile("d:\\a.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
   bResult = WriteFile(hFile1, myRecord, sizeof(myRecord), &dwBytes, NULL);
...       
}

Is there other way to accomplish this task?
0
Comment
Question by:misha051797
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
7 Comments
 
LVL 86

Accepted Solution

by:
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);

0
 

Author Comment

by:misha051797
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;
      
        HANDLE hFile1 = CreateFile("d:\\a.txt", GENERIC_READ|GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
      
      
      
    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;

      SetEndOfFile(hFile1);

      return TRUE;
}
Thank you.
0
 
LVL 86

Expert Comment

by:jkr
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...)
0
Industry Leaders: 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

by:misha051797
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.
0
 
LVL 86

Expert Comment

by:jkr
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...
0
 
LVL 11

Expert Comment

by:alexo
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.

0
 
LVL 86

Expert Comment

by:jkr
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...
0

Featured Post

Technology Partners: 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!

Question has a verified solution.

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

Suggested Solutions

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
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 goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
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.

737 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