我有这个文本文件:
Line 1. "house"
Line 2. "dog"
Line 3. "mouse"
Line 4. "car"
...
我想更改第 2 行。“狗”在新的第 2 行“卡片”中
我该怎么办?
谢谢!
(抱歉我的英语不好)
最佳答案
你的程序可能是这样的:
#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);
}
将此解决方案应用于某些生产系统时,您应该考虑以下事项:
- 最大行长度 1000 是否满足您的需求 - 也许您想提出一种使用
malloc()
为一行动态分配内存的解决方案 - 你应该使用一些随机文件名生成器来生成临时文件并确保它不存在,这样你就不会覆盖现有文件
- 对于大文件,这种方法可能不是最好的,因为您实际上将文件内容存储在内存中两次
关于c - ANSI C - 文本文件 : Modify Line?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23653962/