Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

string - C++ non null terminated char array outputting

I was trying to output a not null terminated char array to a file.

Actual thing is, I am receiving packets and then printing their fields.

Now as these fields are not null terminated, for example, a data segment which has size of 512 but may or may not be completely occupied.

When I write this data to a file I am using simple << overloaded function which does not know any thing about actual data and only looks for termination of data segment.

So, how can I tell the output function to write only this much specific number of bytes?

Instead of using something like this which is expensive to call each time:

enter code here  

bytescopied = strncpy(dest, src, maxbytes);

if (bytescopied < 0) { // indicates no bytes copied, parameter error

    throw(fit);          // error handler stuff here

 } else if (bytescopied == maxbytes) {

    dest[maxbytes-1] = '';   // force null terminator

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to put exactly maxbytes bytes, use write method

stream.write(buffer, maxbytes);

If you can have less bytes in buffer, how do you know how many of them your buffer contains? If '' marks buffer end, you can write:

stream.write(buffer, std::find(buffer, buffer+maxbytes, '') - buffer);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...