1

I got some code and I want improve it to find and replace bytes in file so I want to find all origbytes in FILE and then replace it with newbytes then save file, I know how to open, write and save, but hot I can find bytes in char?

 FILE* file;
 file = fopen("/Users/Awesome/Desktop/test", "r+b");
 int size = sizeof(file)+1;
 char bytes [size];
 fgets(bytes, size, file);
 for (int i=0; i<size; i++){ 
     char origbytes  []  = {0x00, 0x00};
     char newbytes   []  = {0x11, 0x11};
     if (strcmp(bytes[i], origbytes)) //Here the problem
     {
         fseek(file, i, SEEK_SET);
         fwrite(newbytes, sizeof(newbytes), 1, file);
     }
 }
 fclose(file);
Alnitak
  • 334,560
  • 70
  • 407
  • 495
user840250
  • 727
  • 1
  • 8
  • 20

4 Answers4

4

strcmp() is for string compare and not character compare. Two characters can be compared directly

if ( bytes[i] == origbytes[something] )

Also you you should not apply sizeof() on a file pointer to determine file size. You should seek to the end of file using fseek and then query ftell except for binary files. For binary files, use something like fstat

One more thing to note is that fgets returns much before the EOF if it sees a newline. Hence in your code, you may not read entire file contents even after doing the changes that we suggested. You need to use fread appropriately

Community
  • 1
  • 1
Pavan Manjunath
  • 27,404
  • 12
  • 99
  • 125
  • Good answer. Only a small correction: actually [the link to cert](https://www.securecoding.cert.org/confluence/display/seccode/FIO19-C.+Do+not+use+fseek%28%29+and+ftell%28%29+to+compute+the+size+of+a+file) you gave recommends against using `fseek/ftell` for anything except new `fseeks` in the same file, both for binary and text files. So it's best to use `fstat` to get file size in any case. – ash108 May 15 '12 at 13:12
1

Strings are null terminated in the C standard library. Your search data is effectively a zero length string. You want memcmp instead.

memcmp (&bytes [i], origBytes, 2)
Skizz
  • 69,698
  • 10
  • 71
  • 108
1

Firstly sizeof(file) + 1 just returns you the size of a pointer + 1. I don't think you need this for the size of the file. Use this: How do you determine the size of a file in C? Then since you compare bytes (more or less smae as char) you simply compare using =

Community
  • 1
  • 1
Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167
0

you can use fseek and then ftell functions to get the file size, not sizeof.

behe
  • 199
  • 3
  • 16
  • That's more accurate than `sizeof`, but less efficient. Better to just query the file system for the size directly. – benzado May 14 '12 at 23:56