删除结尾的NULL终止符 [英] Remove trailing NULL terminator

查看:114
本文介绍了删除结尾的NULL终止符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大的char数组,其中填充了0.我从套接字读取传入的文件,并将其内容放在缓冲区中.我无法写入所有'\ 0'的缓冲区,因此我分配了一个具有正确大小的新缓冲区并进行写入. 我使用这种方法来做到这一点:

I have a large char array that is filled with 0's. I read an incoming file from a socket and place it's contents in the buffer. I can't write the buffer with all of the '\0's in it, so I allocate a new buffer with the correct size and to write. I used this approach to do that:

int i = 0;
while(buf[i] != '\0'){
    i++;
}
char new[i];
while(i){
    new[i] = buf[i];
    i--;
}
new[0] = buf[0];

尽管这种方法可行,但它似乎并不是最聪明或最优雅的方法.从char数组中删除所有尾随NULL字符的最佳方法是什么?

While this approach works, it doesn't seem like the smartest or most elegant way. What is the best way to remove all of the trailing NULL chars from a char array?

推荐答案

我想更简单的方法是:

size_t len = strlen(buf); // will calculate number of non-0 symbols before first 0
char * newBuf = (char *)malloc(len); // allocate memory for new array, don't forget to free it later
memcpy(newBuf, buf, len); // copy data from old buf to new one

这篇关于删除结尾的NULL终止符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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