我有这个文本文件:
Line 1. "house"
Line 2. "dog"
Line 3. "mouse"
Line 4. "car"
...
我想在新的第2行更改第2行“dog”。“cards”
我该怎么办?
谢谢!
(抱歉我的英语不好)
答案 0 :(得分:2)
您无法内联编辑磁盘文件。你必须遵循以下过程:
将文件数据读取到缓冲区,(fopen()
- > fread()/fgets()
)
然后删除旧文件,(unlink()/remove()
)
然后修改缓冲区中的数据,
将缓冲区写回新文件(fwrite
)
将其重命名为原始文件。 (rename()
)
答案 1 :(得分:0)
你的程序可能是这样的:
#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);
}
将此解决方案应用于某个生产系统时应考虑以下事项:
malloc()
为一行动态分配内存的解决方案