C ++非空终止字符数组输出 [英] C++ non null terminated char array outputting

查看:334
本文介绍了C ++非空终止字符数组输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



实际上,我正在接收数据包,然后打印他们的字段。



现在,由于这些字段不是空值终止的,例如,一个大小为512的数据段,但可能或可能不会被完全占用。



当我写这个数据到文件我使用简单的<<重载函数,它不知道任何关于实际数据的事情,只查找数据段的终止。



那么,我怎么能告诉输出函数只写这么多特定字节数



而不是使用每次调用昂贵的代码:

 在这里输入代码

bytescopied = strncpy(dest,src,maxbytes);

if(bytescopied< 0){//表示没有复制字节,参数错误

throw(fit); //错误处理程序在这里

} else if(bytescopied == maxbytes){

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

}


解决方案

如果您想要精确地 maxbytes 字节,请使用方法

  stream.write(buffer,maxbytes); 

如果你可以在缓冲区中有更少的字节,你怎么知道你的缓冲区包含多少?如果'\0'标记缓冲区结束,您可以写入:

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


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] = '\0';   // force null terminator

}

解决方案

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 '\0' marks buffer end, you can write:

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

这篇关于C ++非空终止字符数组输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆