tags:

views:

49

answers:

3

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);
+1  A: 

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 Ls...

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.

Tyler McHenry
I meaned I've tried to AB -> A....but result shows me AB->A\0..I want to remove the '\0'.... And I tried to "fwrite(" But result shows me 'AA'...Any Other good idea?
neheeee
+1  A: 

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.

Anders K.
A: 

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:

  • Write a complete new copy of the file, then rename it over the old one; or
  • Define a file format where your application can mark data as "deleted", and will ignore it.
caf