0

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.

6
  • If you're just writing binary ostream.write Commented Jun 27, 2019 at 13:10
  • 3
    sizeof(obj._asciiDataLength) is wrong Commented Jun 27, 2019 at 13:10
  • @Mgetz I'm not writing binary, I'm writing ASCII but without strings? Commented Jun 27, 2019 at 13:12
  • then insofar as the char array is zero terminated you can just use operator << to output it doesn't need a string? Commented Jun 27, 2019 at 13:14
  • 1
    You write memcpy(obj._asciiData, s.length()); shouldn't be something like memcpy(obj._asciiData, s.c_str(), s.length()); ? You might want to consider using strncpy cplusplus.com/reference/cstring/strncpy Commented Jun 27, 2019 at 13:20

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

7 Comments

Also, the explicit cast is redundant.
@eerorika Right, I only focused on the faulty part but it is indeed redundant.
Technically insofar as _asciiData is zero terminated they should be able to just use operator << too
@Mgetz Note how the OP creates that struct: memcpy(obj._asciiData, s.length());. Typo (the source is missing, I'd assume s.c_str()) apart, it uses length(), not length() + 1.
@Bob__ I suspect we're seeing an odd snapshot where there are better ways of doing things. Hence the "insofar". I really don't think we have a clear picture.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.