ちょっとばかげた質問がありますが、コードに少し問題があります。ファイルの行を上書きしようとしていますが、これはそれが行うことですが、問題は他のファイル行も上書きすることです。私は C++ Visual Studios 2010 を使用しています。私のコードは以下のとおりです。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const string FILENAME = "DatabaseTest.txt";
fstream& GoToLineI(fstream& file, int num)
{
file.seekg(ios::beg);
for(int i = 0; i < num+1; i++)
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return file;
}
fstream& GoToLineO(fstream& file, int num)
{
file.seekp(ios::beg);
for( int i = 0; i < num; i++)
{
//gets the length of the line.
GoToLineI(file, i);
string s;
file >> s;
long pos = file.tellp();
file.seekp( pos + s.length() );
}
return file;
}
int main()
{
fstream myfile(FILENAME.c_str(), ios::out);
myfile.close();
myfile.open(FILENAME.c_str(), ios::in | ios::out);
myfile << "Usernames:" << endl;
for( int j = 0; j < 101; j++)
myfile << j << endl;
cout << "Where do you want to grab the data from?";
int i = 0;
cin >> i;
GoToLineI(myfile, i);
string line;
myfile >> line;
cout << line << endl;
GoToLineO(myfile, i);
if( myfile.is_open() )
{
cout << "File should be writeable" << endl;
myfile << "This should be at line 75" << endl;
}
myfile.seekp(ios::end);
system("PAUSE");
myfile.close();
return 0;
}
問題は、出力行に到達する場所を見つける方法であるGoToLineOの方法にある可能性があります.GoToLineIを呼び出して、正しい行に到達して出力の表示を開始するまで行の長さを取得します. このコードが生成する出力はそのままです。
72
73
74
This should be at line 75
82
83
84
そして、次のようになります。
73
74
This should be at line 75
76
77
78
79
80
81
どんな種類の洞察やアドバイスも大歓迎です。
編集: 表示されるべき出力の重要な部分のみに変更されました。