I am testing my program to update a number (num_commit) always at the end of the file. This number is used to track how many times the files has been written. I am using lseek/SEEK_END, but I am still trying to figure out how this works. I wrote the following code to test the possibility, but the num_commit seems overwritten. I am looking for help with the correct way of doing this:
#define MAX_PATHNAME_LEN 256
int main()
{
int commit_times = 10;
char pathFile[MAX_PATHNAME_LEN];
sprintf(pathFile, "my_log2.bin");
int filedescriptor = open(pathFile, O_RDWR | O_CREAT, 0777);
int num_segs = 10;
int mods = 200;
const char *segname = "testfil";
char real_segname[128];
strcpy(real_segname, segname); /* in my real program segname is passed into the function */
lseek(filedescriptor, 0, SEEK_END); /* write commit_times always at the end of the file */
write(filedescriptor, &commit_times, sizeof(int));
lseek(filedescriptor, 0, SEEK_SET); /* start writing at the beginning */
write(filedescriptor, &num_segs, sizeof(int));
int name_length = strlen(real_segname);
write(filedescriptor, &name_length, sizeof(int));
write(filedescriptor, real_segname, name_length);
write(filedescriptor, &mods, sizeof(int));
commit_times++; /* increment commit_times */
lseek(filedescriptor, -sizeof(int), SEEK_END); /* then update the commit_times at the end of the file (overwrite the existing number) */
write(filedescriptor, &commit_times, sizeof(int));
close(filedescriptor);
/* now read back the file */
int readfd = open(pathFile, O_RDONLY);
read(readfd, &num_segs, sizeof(int));
read(readfd, &name_length, sizeof(int));
read(readfd, real_segname, name_length);
read(readfd, &mods, sizeof(int));
int num_commit;
read(readfd, &num_commit, sizeof(int));
printf("num_segs=%d, name_length=%d, real_segname=%s, mods=%d, num_commit=%d \n", num_segs, name_length, real_segname, mods, num_commit);
close(readfd);
return 0;
}
Here's my output, as you can see num_commit is overwritten by the mods value:
num_segs=10, name_length=7, real_segname=testfil, mods=200, num_commit=200