1

I'm trying to use fstream to try to read and write at the same time. I read the first line and after that writing in the last sentence of the file.

#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;

}

I think that the program is correct, but the file have some white spaces between the lines that I add to the end of the file(sorry but my reputation is low and I can't upload the image of the file).

By the other hand, I'm trying to create the file for the first time with the fstream, but it's impossible, the file have to exist before to use it. What can I do?.With ifstream and ofstream, if the file don't exist, the program may create the file, but the problem that I have is with the fstream.

1 Answers1

0

This is the solution: 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;

}

I've used the answer of Blacktempel and Simon as example, although is not the same answer. I had a forever loop in the program and I've used the temp variable to solve this, this variable is loaded with the initial value of the end position of the file, before writing in the next position. Because a problem with the method, I can use in the list of arguments of open method, neither "ios::in|ios::out|ios" nor implicit ones(as in the previous example). Because of this, I've added the ios::app value(althoug also is possible to use ios::trunc, but I want to append to end).