问题
I have this text file:
Line 1. "house"
Line 2. "dog"
Line 3. "mouse"
Line 4. "car"
...
I want to change Line 2. "dog" in new Line 2."cards"
how can I do?
thanks!
(sorry for my bad English)
回答1:
Your program could like this:
#include <stdio.h>
#include <stdlib.h>
#define MAX_LINE_LENGTH 1000
int main()
{
FILE * fp_src, *fp_dest;
char line[MAX_LINE_LENGTH];
fp_src = fopen("PATH_TO_FILE\\test.txt", "r"); // This is the file to change
if (fp_src == NULL)
exit(EXIT_FAILURE);
fp_dest = fopen("PATH_TO_FILE\\test.txt_temp", "w"); // This file will be created
if (fp_dest == NULL)
exit(EXIT_FAILURE);
while (fgets(line, 1000, fp_src) != NULL) {
if (strncmp(line, "Line 2.", 7) == 0) {
fputs("Line 2. \"cards\"\n", fp_dest);
printf("Applied new content: %s", "Line 2. \"cards\"\n");
}
else {
fputs(line, fp_dest);
printf("Took original line: %s", line);
}
}
fclose(fp_src);
fclose(fp_dest);
unlink("PATH_TO_FILE\\test.txt");
rename("PATH_TO_FILE\\test.txt_temp", "PATH_TO_FILE\\test.txt");
exit(EXIT_SUCCESS);
}
The following things you should consider when taking this solution into some production system:
- Does the maximum line length of 1000 staisfy your needs - maybe you want to come up with a solution that uses
malloc()
to dynamically allocate memory for one line - You should take some random-filename-generator to generate the temporary file and make sure that it doesn't exist yet, so you don't overwrite an existing file
- With large files this approach is maybe not the best because you effectivly have your file-content twice in memory
回答2:
You cannot edit disk files inline. You have to follow the process of:
reading the file data to buffer, (
fopen()
->fread()/fgets()
)then delete old file, (
unlink()/remove()
)then modify the data in buffer,
write back buffer to a new file, (
fwrite
)rename it to original file. (
rename()
)
来源:https://stackoverflow.com/questions/23653962/ansi-c-text-file-modify-line