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?

2
  • c and c++ are different languages. Pick one you need. Commented Apr 13, 2016 at 4:19
  • done, its C++ that I want. Commented Apr 13, 2016 at 4:21

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.