c++ output問題 iostream

2008-01-21 9:14 pm
點先可以係某一條line到output樣野而又覆蓋之前個句野?

好似咁
[abc.txt]

abc
123
username <-----使用者既名, 唔一定係username, 可能係其他
789 <-----點將e行變成111
bbb
222

改左之後後變成
[abc.txt]

abc
123
username
111
bbb
222

我想整當使用者輸入左一句野(例如: 111)
電腦自動修改使用者既名(例如: username)下面變成111

希望有人答我 thx

回答 (1)

2008-01-22 7:26 pm
✔ 最佳答案
The following code is written with c-style input-output. But the logic is the same.
If you want, you simply replace them with the C++ style outptut.



#include < stdio.h>
#include < stdlib.h>
#include < string.h>
void fcopy(char *file1, char *file2)
{
FILE *f1=fopen(file1,"r"), *f2=fopen(file2,"w");
char li[200];
while(fgets(li,199,f1)!=NULL)fprintf(f2,"%s",li);
fflush(f2); fclose(f1); fclose(f2);
}
int main(int argc, char *argv[])
{
char li[200];
char *msg1="111";
char *file1="test_ios.txt", *file2="test_ios.tmp"; // open text and temp. files
FILE *f1=fopen(file1,"r"), *f2=fopen(file2,"w");
while(fgets(li,199,f1)!=NULL)
{
if(strncmp(li,"Username",8)==0) // use your own criteria for selecting the line
{
fprintf(f2,"%s",li); // write the line
fgets(li,199,f1); // read in next line
fprintf(f2,"%s\n",msg1); // dump line read, write replacement message
} else {
fprintf(f2,"%s",li); // copy line to output
}
}
fflush(f2); fclose(f1); fclose(f2);
fcopy(file2,file1); // copy temp file to original file, to be overwritten
gets(li); // halt display, press a key to continue
}
/* original content of test_ios.txt
Test
Username
888
abc
def
*/
/* final content of test_ios.txt
Test
Username
111
abc
def
*/



收錄日期: 2021-04-13 15:00:50
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20080121000051KK01146

檢視 Wayback Machine 備份