views:

197

answers:

5

I'm going to have two class functions. The first class function opens the file. Then it calls a second function that writes to the file and recursively calls itself. When the second function finishes, the original function closes the file.

Is it possible to do this?

+4  A: 

Yes, that's perfectly possible.

sepp2k
+1  A: 

Yes. Nothing in C++ or the file system will prevent you from doing this.

JSBangs
+5  A: 

Yes, as long as your recursive function has a base case, it will terminate.

func2(int p) {
  if (p == 0) return;
  //write
  func2(--p);
}

func() {
  //open file
  func2(10);
  //close file
}
verhogen
You are using post decrement in `func2(p--)` so you will call the next func2 with the same value this func2 was called with so your recursion will never terminate. You need to either do `func2(--p)` or `func2(p - 1)`.
R Samuel Klatchko
I _knew_ there was a reason I preferred `recursive(i - 1)` to `recursive(i--)` or `recursive(--i)`. That was it. @R Samuel is right, the code you give will iterate forever (or perhaps until a stack overflow happens if the compiler doesn't optimize this). I prefer `func2(p - 1)` because a) there's no reason to use `--`, since we never need the value of `p` again, and b) we have no risk of using `p--` and expecting it to work, even though `p--` returns the original value of `p`, causing this to recurse forever.
Chris Lutz
+3  A: 

Yes because the write calls are sequencial even if that sequence is defined recursivly. The file object sees nothing but a linear serise of write calls, regardless.

Chris H
+8  A: 

Sure, as long as you pass the file handle/object to the recursive function:

void recursion(int data, int maxdepth, ostream &os)
{
    // must eventually break out
    if (maxdepth == 0)
        return;

    // write data
    os << data << std::endl;

    // and call one deeper
    recursion(data + 1, maxdepth - 1, os);
}

void start(const char *filename)
{
    std::ofstream os(filename);

    recursion(0, 100, os);
}
R Samuel Klatchko
+1 for a code sample
Bill
I prefer to do the level backwards. That way, the caller sees `recursion(100, os)` and knows that it will recurse 100 levels deep. That's more informative than seeing `recursion(0, os)` and having to know that it will recurse 100 - 0 = 100 levels deep. But that's just me.
Chris Lutz
@ChrisLutz - I like that idea as that lets the caller determine how far to recurse. I actually made the data separate from the maxdepth to show how they can be independent (because while this toy example the data is a counter, in a real example, it could be something else).
R Samuel Klatchko