C Programming - File I/O Problem

2007-08-23 7:28 am
I want to write a C program which can change a text file content. For example, I want to replace all the character "&&&" in the text file to "123" and then save it to the same file. How can I do it? Thanks.

回答 (2)

2007-08-24 7:58 pm
✔ 最佳答案



因為文字檔案的容量很難預計,建議用「即時傳譯」的方式,就是讀一段、處理一段。



演算法 Algorithm




用fgets()從文字檔讀一段以"\n"為分界的文字
用strstr()來搜尋目標字串
用strcat()/strncat()等以連接替換字串
重複2及3直至全段字串已掃瞄完畢
用fputs()把字串輸出至檔案
重複1至5直至全個檔案已掃瞄完畢




程式原碼 Program Source Code






圖片參考:http://i206.photobucket.com/albums/bb265/a048042l/replstr01.gif


圖片參考:http://i206.photobucket.com/albums/bb265/a048042l/replstr02.gif


圖片參考:http://i206.photobucket.com/albums/bb265/a048042l/replstr03.gif


圖片參考:http://i206.photobucket.com/albums/bb265/a048042l/replstr04.gif


圖片參考:http://i206.photobucket.com/albums/bb265/a048042l/replstr05.gif






原碼下載 Download




圖片參考:http://i206.photobucket.com/albums/bb265/a048042l/rightarrow.gif
replstr.c



編譯 Compilation



Microsoft Visual C++ 或 任何與 ANSI C 相容之編譯器



執行 Execution



replstr



顯示「線上協助」(on-line help)



replstr myfile.txt = "&&&" 123



把“myfile.txt”檔內的“&&&”字串換成“123”



replstr myfile.txt "c:\My Documents\yourfile.txt" 123 " "



把“myfile.txt”檔內的“123”字串換成空格,結果輸出至“c:\My Documents\yourfile.txt”,而“myfile.txt”則維持原狀


參考: 原創
2007-08-23 9:26 pm
You can first read all the characters in the file into the character array. Then do the replacement just using for-loop. Then open the same file and write the characters onto the files.

FILE* f = open(file_name, ''r+'');
// read the files

// replace string

freopen(f, file_name, ''w+'');
// write onto the file

fclose(f);


收錄日期: 2021-04-23 17:13:54
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20070822000051KK06379

檢視 Wayback Machine 備份