Reputation: 7466
I have the following code in C. I am trying to look for a line starting with a known word, in order to write back that line with new information. The problem I find is that the stream fp is already after the line I want to edit the moment I find it, so I need to go back to that line in order to write it. How could I do it? Thanks.
FILE *fp;
char line[256];
char description[128];
memset(description, 0, sizeof (description));
if (!(fp = (FILE*) fopen("/etc/samba/smb.conf", "r+"))) {
printf("Error opening smb.conf\n");
return -1;
}
while (fgets(line, sizeof line, fp)) {
if (!strncmp(line, "comment =", 9)) {
sscanf(line, "comment = %[^\t\n]", description);
printf("Old comment found: %s\n",description);
fprintf(fp, "comment = %s\n", "New Comment here");
}
}
fclose(fp);
Upvotes: 0
Views: 1926
Reputation: 490128
Assuming the file isn't tremendously huge, the easiest way is probably to read the entire file into an array of strings, modify whichever of those strings you want, then write them all back out to disk.
Edit: I do feel obliged to point out that unless you need quite a bit beyond what your question suggests, sed
might be a better choice than writing your own program from the ground up.
Upvotes: 2
Reputation: 206689
Even if there was a way to "rewind to previous line", your approach would not work in general. It would only work if you're replacing with a line of the exact same length. (You could make it work for inserting lines shorter than the original with whitespace padding, but not if you want to insert more data than was originally there.)
Create a new file, copy everything there (modifying as you see fit), and replace the original once you've successfully completed.
Alternative, read the file in memory (modifying as you need along the way), and overwrite the original.
You can't "insert" something in the middle of a file without something like the above.
Upvotes: 4