[英]ANSI C - Text File: Modify Line?
我有這個文本文件:
Line 1. "house"
Line 2. "dog"
Line 3. "mouse"
Line 4. "car"
...
我想在新的第 2 行中更改第 2 行。“狗”。“卡片”
我能怎么做?
謝謝!
(對不起,我的英語不好)
您不能內聯編輯磁盤文件。 您必須遵循以下流程:
讀取文件數據到緩沖區,( fopen()
-> fread()/fgets()
)
然后刪除舊文件,( unlink()/remove()
)
然后修改緩沖區中的數據,
將緩沖區寫回新文件,( fwrite
)
將其重命名為原始文件。 ( rename()
)
你的程序可能是這樣的:
#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()
為一行動態分配內存的解決方案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.