intrigued_66
intrigued_66

Reputation: 17240

Write C++ array to file, avoiding creating a std::string

I have a struct representing ASCII data:

struct LineData
{
    char _asciiData[256];
    uint8_t _asciiDataLength;
}

created using:

std::string s = "some data here";
memcpy(obj._asciiData, s.length());
obj._asciiDataLength = s.length();

How do I write the char array to file as ASCII, in the lowest latency? I want to avoid the intermediary stage of creating a temporary std::string.

I tried:

file.write((char *)obj._asciiData, sizeof(obj._asciiDataLength));
file << std::endl;

but my file just contains '0' each line.

Upvotes: 0

Views: 118

Answers (1)

Hatted Rooster
Hatted Rooster

Reputation: 36473

That's because sizeof(obj._asciiDataLength) is probably 1 on your system so only one character is written. You want the actual length, not the size of the uint8_t:

file.write(obj._asciiData, obj._asciiDataLength);

Upvotes: 4

Related Questions