Reputation: 101
All I want to do is write one long int to offset 0x18 and another separate long int to offset 0x1C into a file I've opened. These offsets always contain the relevant data for the file format I'm processing, so there's no need to worry about that--all I need to do is make the value at these addresses equal to some specified number. I have no problem opening the file, but I'm not sure how to accomplish this since I'm not very experienced with C.
Right now I'm opening the file in write mode with fopen(), seeking to 0x18 with fseek, writing "XXXXX" with fputs (XXXXX is just some number), seeking again to 0x1C, doing the same thing again, and closing the file. Not only do I feel like this approach is mistaken, it also does nothing and I have no idea why. Am I right and I should be going about this some other way, or am I just missing something?
EDIT: Code:
void modify_data(unsigned long int samp1, unsigned long int samp2, char fname[]) {
FILE * newfile;
newfile = fopen(fname, "w");
fseek(newfile, 0x18, SEEK_SET);
fputs("180000", newfile); // 180000 is a placeholder while I test
fseek(newfile, 0x1C, SEEK_SET);
fputs("600000", newfile); // 600000 is a placeholder while I test
fclose(newfile);
}
int main(int argc, char * argv[]) {
char fname[sizeof(argv[1])];
strcpy(fname, argv[1]);
modify_data(0, 0, fname); // the first two arguments are placeholders while I test
return 0;
}
Upvotes: 0
Views: 1692
Reputation: 50774
You probably want this:
#include <stdio.h>
void modify_data(unsigned int samp1, unsigned int samp2, char fname[])
{
FILE * newfile;
newfile = fopen(fname, "r+"); // or "r+b" on Windows
if (newfile != NULL)
{
printf("Could not open file");
return;
}
fseek(newfile, 0x18, SEEK_SET);
fwrite(&samp1, sizeof (unsigned int), 1, newfile);
fseek(newfile, 0x1c, SEEK_SET);
fwrite(&samp2, sizeof (unsigned int), 1, newfile);
}
int main(int argc, char * argv[])
{
modify_data(0, 0, argv[1]); // the first two arguments are placeholders while I test
return 0;
}
Upvotes: 1
Reputation: 50774
Non error checking non tested code fragment:
long value1 = 18000;
long value2 = 60000;
FILE *fp = fopen("thefile", "r+"); // or "r+b" on Windows
fseek(fp, 0x18, SEEK_SET);
fwrite(&value1, sizeof long, 1, fp);
fseek(fp, 0x1c SEEK_SET);
fwrite(&value2, sizeof long, 1, fp);
If the size of long
is not 32 bits on your platform, you need to subsitute long
with an appropriate 32 bit type, most likely int
.
Your solution with fputs
wont work.
fputs("180000", newfile);
writes the string "180000" to the file and not the 32 bit value 18000.
Upvotes: 2