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);
2
  • As a reminder, if you have answers to your questions that are good, you should accept one. Commented May 14, 2012 at 12:42
  • 3
    sizeof does not give the size of files. Commented May 14, 2012 at 12:59

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Good answer. Only a small correction: actually the link to cert 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.
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)

Comments

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 =

Comments

0

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

1 Comment

That's more accurate than sizeof, but less efficient. Better to just query the file system for the size directly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.