(ファイルが既に存在する場合) 最初の数値を 1 つ増やし、関数のパラメーターをファイルの末尾に追加する関数を作成しています。
例:
- 追加 (4,9);
- 追加 (5,6);
1 のファイルの内容: 1 \n 4 \n 9
2 のファイルの内容: 2 \n 4 \n 9 \n 5 \n 6
int append (int obj, int objType) {
ifstream infile;
infile.open("stuff.txt");
if (infile.fail()){
infile.close();
ofstream outfile;
outfile.open("stuff.txt");
outfile << 1 << endl << obj << endl << objType;
outfile.close();
}
else {
int length = 0;
while (!infile.eof()){
int temp;
infile >> temp;
length ++;
}
infile.close();
infile.open("stuff.txt");
int fileContents[length];
int i = 0;
while (!infile.eof()){ /*PROGRAM DOES NOT ENTER HERE*/
infile >> fileContents[i];
i ++;
}
infile.close();
ofstream outfile;
outfile.open("stuff.txt");
fileContents[0] +=1;
for (i = 0; i < length; i++){
outfile << fileContents[i] << endl ;
}
outfile << obj << endl << objType;
}
プログラムは 2 番目の while ループに入らないため、内容が配列にコピーされてからファイルにコピーされることはありません。問題が何であるか、またはそれを修正する方法が正確にわかりません。どんな助けでも大歓迎です。:)