Kurausukun Kurausukun - 2 months ago 20
C Question

How to Write to a Specific Address in a File in C

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;
}

Answer

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;
}