问题
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];
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?
回答1:
I suppose easier way to do this is:
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
回答2:
My first idea would be: count the characters you receive from your stream, then write that amount of bytes at once to your file.
If that is not possible, we get to the less smart approach:
int i = BUFFER_SIZE - 1;
while((i>=0) && (buffer[i--] == '\0'));
++i;
After that, i
contains the length of your buffer.
回答3:
You can take the advantage of the NULL property. Just copy the this data without NULL character. Like this len = strlen(buf); // it will make sure you are reading only total_char + 1 Now copy only len-1 char from this buffer to the file. If you want to you can prepare the new buffer too.
来源:https://stackoverflow.com/questions/26069167/remove-trailing-null-terminator