2

suppose I want to write in a .txt file in following format

start-----
-----A----
----------
-B--------
-------end

I've 3 functions that write the parts to file; start to A, A to B then B to end. My function call are going to be in this order

Func1(starts writing from start of file)
{ }
Func2(needs pointer to position A for writing to file)
{ }
Func3(needs pointer to position B for writing to file)
{ }

Take Fun1 and Func2 for example, Func1 will end writing at A, but the problem is that Func2 needs to go forward from point A. How can I pass a pointer of position A to Func2 so that it'll be able to continue writing from position A in the file?

Masroor
  • 1,484
  • 3
  • 14
  • 23

2 Answers2

3

Since this is c++ we could use file stream object from the standard c++ library.

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

void func1(ofstream& f)
{
  f << "data1";
}

void func2(ofstream& f)
{
  f << "data2";
}

int main () {
  ofstream myfile ("example.txt");
  if (myfile.is_open())
  {
    func1(myfile);
    func2(myfile);
    myfile.close();
  }
  else cout << "Unable to open file";
  return(0);
 }

However this approach is universal. When you are working with file, you get some file identificator. It could be a FILE struct, Win32 HANDLE etc. Passing that object between functions will allow you to continuously write the file.

Ari0nhh
  • 5,720
  • 3
  • 28
  • 33
1

Not sure how you're outputting to a file (using which output method), but normally, the file pointer keeps track itself where it is up to.

eg using fstream

ofstream outFile;
outFile.open("foo.txt");
if (outFile.good())
{
    outFile<<"This is line 1"<<endl
           <<"This is line 2"; // Note no endl

    outFile << "This is still line 2"<<endl;

}

If you pass the outFile ofstream object to a function, it should maintain position in the output file.

Previously answered: "ofstream" as function argument

Community
  • 1
  • 1
Guy S
  • 457
  • 4
  • 9