【问题标题】:c++, fstream and seekp and seekg, weird programc++, fstream and seekp and seekg, 奇怪的程序
【发布时间】:2015-07-27 06:53:17
【问题描述】:

我正在尝试使用 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。

【问题讨论】:

标签: c++ visual-studio-2010


【解决方案1】:

这是解决方案: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 方法的参数列表中使用,既不是 "ios::in|ios::out|ios" 也不是隐含的(如前面的例子)。因此,我添加了 ios::app 值(虽然也可以使用 ios::trunc,但我想追加到结尾)。

【讨论】:

    猜你喜欢
    • 2013-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2012-12-29
    • 1970-01-01
    相关资源
    最近更新 更多