开发者

Can a recursive function write to a file in C++?

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?


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);
}


Yes, that's perfectly possible.


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
}


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜