ruckpositiv
ruckpositiv

Reputation: 45

Reading and writing a file with special characters in c

Using the C language, I am trying to manipulate some files generated by openssl and containing a lot of (very) special characters. But the end of file seems to be prematurely detected. For example see an extract of my program, that is supposed to copy a file to another :

(for simplicity reasons I do not show the test of the opening of the file but I do that in my program)

char msgcrypt[FFILE];
FILE* fMsg = fopen(f4Path,"r");
while(fgets(tmp,FFILE,fMsg) != NULL) strcat(msgcrypt,tmp);
fclose(fMsg);
FILE* fMsg2 = fopen(f5Path,"w");
fprintf(fMsg2,"%s",msgcrypt);
fclose(fMsg2);

here is the content of the file located at f4Path :

Salted__X¢~xÁïÈú™xe^„fl¯�˜<åD

now the content of the file located at f5Path :

Salted__X¢~xÁïÈú™xe^„fl¯

Notice that 4 characters are missing.

Do someone have an idea?

Upvotes: 2

Views: 4434

Answers (3)

Matt
Matt

Reputation: 7160

That character it stops on I copied into a hex editor, and it ends up being EF BF BD, a BOM if I'm not mistaken. As a result, reading the file as a text file fails. I don't see any NULL characters (unless copying and pasting got rid of them).

The answer (as has already been discussed) is to not treat it as a text file, and avoiding the str functions won't do any harm either.

The first thing I'd do though is add a check for how may characters are read, that way you'll know where the data is being truncated. Right now it could be in any of: read, strcat, write.

Upvotes: 1

fge
fge

Reputation: 121710

strcat tries and copy a nul-terminated char *. Which means, if it encounters a 0, which it probably has done here, it will stop copying.

You'd better use open read, memcpy and write.

Upvotes: 2

cnicutar
cnicutar

Reputation: 182639

But the end of file seems to be prematurely detected

Sounds familiar.

  • Use fopen(f4Path, "rb") when opening the file. This has real significance on Windows.
  • Don't use string functions (fprintf, strcat, fgets etc) they will choke on NUL characters. Use fread and fwrite instead.

Upvotes: 7

Related Questions