将输出放入指定的文件行时,会覆盖额外的文件行

时间:2013-04-10 02:51:56

标签: c++ visual-studio-2010 output fstream overwrite

嘿,我有一个愚蠢的问题,但我的代码有点问题。我试图覆盖文件的一行,这是它的作用,但问题是它也会覆盖其他文件行。我正在使用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

非常感谢任何形式的见解或建议。

编辑:仅更改为应显示的输出的重要部分。

1 个答案:

答案 0 :(得分:0)

如果你寻找文件中的某个位置,然后开始在那里写,你写的东西会覆盖与你写的完全相同的字节数 - 有点像编辑器总是处于覆盖模式而不是插入模式。

如果您希望结果保留为简单的文本文件,您可以做的就是将数据复制到新文件,将新数据插入正确的位置,然后将原始文件中的剩余数据复制到新文件中插入新数据后的文件。

如果您希望该结果与原始名称相同,您可以选择一些 - 您可以将整个结果复制回现有文件,或者(如果您不担心多重困难的可能性)您可以删除原始文件,并将新文件重命名为旧名称。