Reputation: 746
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);
Upvotes: 1
Views: 2927
Reputation: 199
you can use fseek and then ftell functions to get the file size, not sizeof.
Upvotes: 0
Reputation: 28535
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
Upvotes: 4
Reputation: 35408
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 =
Upvotes: 1
Reputation: 71070
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)
Upvotes: 1