ANSI C-文本文件:修改行? [英] ANSI C - Text File: Modify Line?
本文介绍了ANSI C-文本文件:修改行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个文本文件:
Line 1. "house"
Line 2. "dog"
Line 3. "mouse"
Line 4. "car"
...
我要更改第2行.在新的第2行中将狗"更改为卡片".
I want to change Line 2. "dog" in new Line 2."cards"
我该怎么办?
谢谢!
(对不起我的英语不好)
(sorry for my bad English)
推荐答案
您的程序可能会这样:
#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:
- 最大行长是否满足您的需求1000-也许您想提出一种使用
malloc()
为一行动态分配内存的解决方案 - 您应该使用一些random-filename-generator来生成临时文件,并确保它不存在,以免覆盖现有文件
- 对于大文件,这种方法可能不是最佳方法,因为您实际上两次将文件内容存储在内存中
- 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
这篇关于ANSI C-文本文件:修改行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文