Reputation: 11
I'm trying to replce some letter with the below code.
But, the result shows "ANULL" not "A"... How can I remove the NULL space...
ps. I'm modifying binary file information.
char *pos = NULL;
if(NULL != (posFind = strstr(fp, "AB");
strncpy(&fp->base[0], "A", 2);
if(_fseek64(fp, 0, SEEK_SET)!= 0) return ZD_ERROR_IO_FAILED;
fwrite(&fp->base[0], 2, 1, fp);
Upvotes: 0
Views: 1047
Reputation: 239321
You can't remove a sequence of characters from the middle of a file. You can only truncate the end of the file.
This means that the only way to do what you want (remove a single byte) is to move every following bit of data in the file back by one byte (by reading and writing it all), then truncate the end of the file to shorten it by one byte.
Suffice it to be said, usually people avoid this. The usual alternatives are:
Upvotes: 0
Reputation: 36092
Seems your if statement looks a bit weird
if(NULL != (posFind = strstr(fp, "AB");
strncpy(&fp->base[0], "A", 2);
the strstr cannot be used to search for a string in a file, you would need to load the file and search for the character sequence in the buffer, replace, then write the buffer back, alternative find the offset in the loaded buffer and then position the file pointer to that same file spot to write the replacement string if the replacement string has same length.
it is also not recommend to fiddle directly with the file pointer members, instead treat the FILE struct as an opaque type.
Upvotes: 1
Reputation: 76760
You mean it writes "A\0"
(an A
followed by a zero byte), yes? Not literally an A
, followed by an N
and a U
and two L
s...
Simply change your fwrite
call to:
fwrite(&fp->base[0], 1, 1, fp);
Note the change of 2 to 1. This tells fwrite
to write only one byte from the given data, rather than two. fwrite
does not deal with C-strings the way that strcpy
and friends do; it deals with raw byte arrays, so it has no special treatment for the null byte. If you tell fwrite
to write some bytes, and it encounters a null byte, it will happily write the null byte and keep on going.
Upvotes: 1