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

c++, fstream and seekp and seekg, weird program

本文关键字:程序 seekp fstream c++ seekg      更新时间:2023-10-16

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

解决方案如下: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,但我想添加到末尾)。