c ++,fstream和seekp and seekg,奇怪的程序

时间:2015-07-27 06:53:17

标签: c++ visual-studio-2010

我试图使用fstream同时尝试读写。我读了第一行,然后写了文件的最后一句。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(){

    int pos1=0,pos2=0;
    string cadFile;

    fstream fs("ejemplo.txt");

    do{

        fs.seekg(pos1,ios::beg);
        getline(fs,cadFile);
        pos1=fs.tellg();
        fs.seekp(pos2,ios::end);
        fs<<cadFile; 
        pos2=fs.tellp();
        cout<<pos1<<"-"<<pos2<<"-"<<cadFile<<endl;

    }while(!fs.eof());

    fs.close();

    system("pause");
    return 0;

}

我认为该程序是正确的,但是文件在我添加到文件末尾的行之间有一些空格(抱歉,但我的声誉很低,我无法上传文件的图像)。

另一方面,我试图用fstream第一次创建文件,但这是不可能的,文件必须存在才能使用它。我该怎么办?。使用ifstream和ofstream,如果文件不存在,程序可能会创建文件,但我遇到的问题是fstream。

1 个答案:

答案 0 :(得分:0)

这是解决方案:int main(){

int pos1,pos2,temp;
string cadFile;

temp=1;
pos1=pos2=0;

fstream fs("ejemplo4.txt",ios::in|ios::out|ios::app);

fs.seekg(pos1,ios::beg);

while(getline(fs,cadFile)&&pos1<temp){

    pos1=fs.tellg();

    fs.seekp(pos2,ios::end);
    if(pos2==0) temp=fs.tellp();
    fs<<cadFile<<endl; 
    pos2=fs.tellp();

    cout<<pos1<<"-"<<pos2<<"-"<<cadFile<<endl;
    fs.seekg(pos1,ios::beg);

};

fs.close();

system("pause");
return 0;

}

我以Blacktempel和Simon的答案为例,虽然答案不尽相同。我在程序中有一个永久的循环,并且我使用了temp变量来解决这个问题,在写入下一个位置之前,这个变量加载了文件结束位置的初始值。因为方法有问题,我可以在open方法的参数列表中使用,而不是&#34; ios :: in | ios :: out | ios&#34;也不是隐含的(如前例所示)。因此,我添加了ios :: app值(虽然也可以使用ios :: trunc,但我想追加到最后)。

相关问题