I have a file a.txt
:
name1 = value1
name2 = value2
name3 = value3
name4 = value4
name5 = value5
I want to update the string value3
to 89
. I have written the following program to achieve this:
#include <stdio.h>
#include <string.h>
#define MAX_LEN 64
int main(void)
{
FILE *fp = fopen("a.txt", "r+");
char line[MAX_LEN];
long l = 89;
while (fgets(line, MAX_LEN, fp)) {
if (strncmp(line, "name3", 5) == 0) {
fseek(fp, -1 * (strlen(line)), SEEK_CUR);
sprintf(line, "name3 = %ld", l);
fputs(line, fp);
goto close;
}
}
close:
fflush(fp);
fseek(fp, 0, SEEK_END);
fclose(fp);
}
Although the value is updated, I am not sure how to remove the rest of the trailing characters: lue3
. This is what I get after executing the program:
name1 = value1
name2 = value2
name3 = 89lue3
name4 = value4
name5 = value5
Could someone please let me know how to go about this? Sure, I could append a bunch of t
s to the second argument of sprintf()
to clear out the trailing chars, but that doesn’t seem cool. Also, is there any better way to write this program? Thanks in advance.
7
Unfortunately, bytes in the middle of a file can be overwritten, but there is no way to insert or delete bytes such that the remaining bytes of the file are shifted unchanged.
I think it is important to consider how the configuration file is going to be used. If it is ‘human writable’ then it would indeed be uncool to require that each value have a bunch of spaces after it.
Typically, the easiest way to achieve what you are trying to do is to read and parse the entire file, make the changes you want to make, then write it back out. This is appropriate in all cases where the configuration file is relatively small and updates are relatively infrequent.
I would assume that you already have some code that reads the configuration file into a key/value map of some kind for easy access. Adding an additional function to update a specific value and then write them all back out would not be too much extra work.
If that is not how things are set up, another way is to do the following: read in each line, modify the line if necessary, then write the line to a temporary file. Once done, copy the temporary file over the original.
However I could imaging cases where the configuration file is large, is written often, and is not considered human writeable. In that case, it might be appropriate to consider other methods. For example, one could make each value field exactly 15 characters long. When a value field is written, always write exactly 15 characters padded appropriately with spaces.
1