at a specific location, say, at byte offset x?
C++ code to write a binary file?
The two previous answers show you how to do it using C. In C++ you tend to use objects whenever possible. This page shows you how to write binary data files using streams:
http://courses.cs.vt.edu/~cs2604/fall00/...
Here is an example from the page:
#include %26lt;fstream.h%26gt;
...
class Data {
int key;
double value;
};
Data x;
Data *y = new Data[10];
fstream myFile ("data.bin", ios::in | ios::out | ios::binary);
// This is how you seek to a location or your offset
myFile.seekp (location1);
myFile.write ((char*)%26amp;x, sizeof (Data));
...
myFile.seekg (0);
myFile.read ((char*)y, sizeof (Data) * 10);
Reply:when you open file use 'b' option to specify its a binary open.
#include %26lt;stdio.h%26gt;
ret = fopen( name, options )
r
open for reading.
w
open for writing.
a
open for appending.
r+
open for both reading and writing. The stream will be positioned at the beginning of the file.
w+
open for both reading and writing. The stream will be created if it does not exist, and will be truncated if it does exist.
a+
open for both reading and writing. The stream will be positioned at the end of the existing file content.
rb
open for reading. The 'b' indicates binary data (as opposed to text); by default, this will be a sequential file in Media 4 format.
wb
open for writing. The 'b' indicates binary data.
ab
open for appending. The 'b' indicates binary data.
and Use seek/tellg to reach/get at the offset.
Reply:FILE * pFile = fopen("filename.ext", "r+b");
fseek(pFile, thePosition, SEEK_SET);
fwrite(pData, dataSize, dataCount, pFile);
fclose(pFile);
If you want to write past the end of the file or insert/delete data then you're going to have to load the file into memory, make the changes and then write out a new file.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment