我想實作以下目標:我必須在具有以下結構的檔案(例如 txt)中管理一個資料庫:X,X,X,X,X 在這個資料庫中,我希望能夠修改一行,其中當我在代碼中撰寫要更改的行時,效果很好。但是我希望能夠在運行程式期間撰寫該行。重要提示:當您輸入行值時,您必須將 . 到最后不過如此。不會進入檔案。此外,您不知道輸入有多長。這是有效的:在 Main 中,值是預先給定的:
char file[50];
scanf("%s",file);
char tmp[]="temp.txt";
char a[]="2,2,2,2,2";
char b[]="9,9,9,9,9";
javitas(file,tmp,a,b); // this will modify the line a to b in the file
步驟:
#define sorhossz 500
void javitas(char filename1[], char filename2[], const char *str, const char *replace) {
FILE *in = fopen(filename1,"r ");
FILE *out = fopen(filename2,"w ");
size_t strl;
char line[sorhossz];
strl = strlen(str);
while (fgets(line, sizeof(line), in)) {
char *y, *x = line;
while ((y = strstr(x, str))) {
fwrite(x, 1, y - x, out);
fputs(replace, out);
x = y strl;
}
fputs(x, out);
}
rewind(out);
rewind(in);
while (fgets(line, sizeof(line), out))
{
char *x = line;
fputs(x, in);
}
fclose(in);
fclose(out);
}
但我想在運行程序中以某種方式在 Main 中給出 'a' 和 'b':
char a[50]; // 50 is a random number I was triing with
char b[50];
printf("Give the line you want to modify\n");
scanf("%[^.]%*c",a);
printf("Give the line you want to modify to\n");
scanf("%[^.]%*c",b);
javitas(file,tmp,a,b);
when i try to give the values from the input, i write "2,2,2,2,2." for a and "9,9,9,9,9." for b. Dont forget that the . is not making into the string. After that, I can printf these strings inside the procedure so I guess the procedure understand the input value, however it does not modify the line 'a' to line 'b' in the file. Could you please help?
and this is a file im testing on: (I named it qqq.txt but it doesnt matter)
9,9,9,9,9
hel,az,de,5,k
0
ennyi,annyi,amannyi,helo,ot 22
1,2,3,4,5
1,2,2,2,3
ez,az vegre, sikerult, 3 sort illeszteni, a fileba
peti,egy,kiraly,helo,5om, 5 helo 5, 5 ezaz
egy,ketto,harom,negy,ot
helo,helo,lusta,vagyok,irni
meg,egyszer,hatha,most,sikerul
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
1,1,1,1,1
2,2,2,3,3
helo,belo,ize,de,4
If the text file doesnt exits, it will be created before the menu. Sorry for being hungarian here and there, but I hope the main thing is understandable.
uj5u.com熱心網友回復:
當我嘗試從輸入中給出值時,我
"2,2,2,2,2."為a
審查 scanf("%[^.]%*c",a);
此呼叫和先前 scanf()呼叫不消耗輸入行的尾隨'\n',因此在這種情況下a變為"\n2,2,2,2,2"。
一個簡單的解決方法是scanf(" %[^.]%*c",a);(注意空格)使用像'\n'.
更好的代碼會使用寬度限制,掃描'.'并檢查結果,也許'\n'
char a[50];
if (scanf(" I[^.].%*1[\n]",a) == 1) Success(); else Fail();
更健壯的代碼根本不會使用scanf(),而是使用讀取用戶輸入行,fgets()然后處理字串。
可能存在其他問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/343570.html
上一篇:如何用?替換空格在字串(ReactJS)中并在HTML中呈現?
下一篇:如何在R中創建字串組合
