Hi,
So I happened to be in a generous mood as I passed by, here's
what I came up with, I've tried to include explanations as
comments.
Code:
char *k;
int line_no = 0;
/*
* The delimiting characters shall be the " and a space
*/
char Delim[] = "\" ";
char strline[MAXLINE];
char search_for[] = "mike";
int replace_with = 22;
FILE *fileptr;
fileptr = fopen("name.cfg", "r+");
while(fgets(strline, MAXLINE, fileptr))
{
line_no++;
if ((strstr(strline, search_for)) != NULL)
{
int i = 0;
char replacement[MAXLINE];
i = strlen(strline);
/*
* The code where the strtok() function is called is
* unnecessary here -- it is just a proof-of-concept
* ;) The delimiters are the " and a space so
* you just supply the second argument of strtok
* with a string containing ALL of the EXPECTED
* delimiting characters for example if the
* delimiting characters were a colon ( : ) OR a
* comma (,) OR a period (.) then Delim would need
* to be defined like this:
*
* char Delim[] = ":,.";
*
* I hope that makes strtok clear otherwise in this
* simple case I illustrate (simple search and replace)
* it is not really needed.
*/
k = strtok(strline, Delim); /* k is now mike */
k = strtok(NULL, Delim); /* k is now the number assoc with mike */
/*
* If you want to be sure, you could slot in a printf
* statement to see what k is -- it should be the value
* associated with "mike".
*
* Next we build up the line we want to replace (for simplicity
* we shall replace the whole line but only changing the number
* associated with the name)
*/
sprintf(replacement, "\"mike\" \"%d\"", replace_with);
/*
* The (possibly) trickier part: replacing the contents
* of the file. Here you use the functions ftell and fseek
* to set the file pointer to the beginning of the line
* you want to replace. That is why we needed the initial
* length of the line -- to know exactly where to place the
* file pointer. So we overwrite the old value with the new
* one. To leave things simple, we'll assume that the number
* associated with the name comprises of TWO digits. So when
* we overwrite the old value, it gets completely overwritten
* Food for thought: If the number associated with the name is
* more than 2 digits, what would you do? I leave that to you.
*
* Look up the documentation on fseek, it's not hard.
*/
fseek(fileptr, ((ftell(fileptr))-i), SEEK_SET);
/*
* The stream pointer is now at the beginning of the line,
* we replace the old line
*/
fprintf(fileptr, "%s\n", replacement);
break;
}
}
fclose(fileptr);
}
You might want to check if the fopen() failed too -- usually good
for debugging.
Have fun,
Gerald.