C ++ std :: ofstream - Move put pointer

I am writing some data to a file. Sometimes I want to write a block of data from memory, and then move the pointer to 1, 2, or 3 bytes in order to keep the data format at 4 bytes.

I could create a new data block containing zeros and write this, but that seems unnecessary and awkward. How to transfer the pointer to 1, 2 or 3 bytes?

I'm not sure how to do this, because if I call seekp(), will I move the pointer outside the current file size? If I assume I am ofstream.write()handling this correctly? that is: does it somehow resize the file when writing data?

+4
source share
2 answers

, - , , 4 .

#include <fstream>

using namespace std;

struct data
{
    char first;
    char second;
};

int _tmain(int argc, _TCHAR* argv[])
{
    ofstream outFile;
    data data1;
    data data2;

    data1.first = 'a';
    data1.second = 'b';
    data2.first = 'c';
    data2.second = 'd';

    outFile.open("somefile.dat");

    outFile.write(reinterpret_cast<char*>(&data1), sizeof(data));
    outFile.write(reinterpret_cast<char*>(&data2), sizeof(data));

    outFile.close();

    return 0;
}

, struct 4 . , .

seekp, , , , , .

    outFile.write(reinterpret_cast<char*>(&data1), sizeof(data));
    outFile.seekp(2, ios_base::cur);
    outFile.write(reinterpret_cast<char*>(&data2), sizeof(data));
    outFile.seekp(2, ios_base::cur);

data1, data2. , . 0 seekp, .

, . , . :

#include <fstream>

using namespace std;

struct data
{
    char first;
    char second;
};

void WriteWithPadding(ofstream* outFile, data d, int width);

int _tmain(int argc, _TCHAR* argv[])
{
    ofstream* outFile = new ofstream();
    data data1;
    data data2;

    data1.first = 'a';
    data1.second = 'b';
    data2.first = 'c';
    data2.second = 'd';

    outFile->open("somefile.dat");

    WriteWithPadding(outFile, data1, 4);
    WriteWithPadding(outFile, data1, 4);

    outFile->close();
    delete outFile;

    return 0;
}

void WriteWithPadding(ofstream* outFile, data d, int width)
{
    if (sizeof(d) > width)
        throw;

    width = width - sizeof(d); // width is now amount of padding required
    outFile->write(reinterpret_cast<char*>(&d), sizeof(data));

    // Add Padding
    for (int i = 0; i < width; i++)
    {
        outFile->put(0);
    }
}
+1

, , , ios::binary, , .

, . , , .

, - , (?), .

, .

0

Source: https://habr.com/ru/post/1616288/


All Articles