AAA
AAA

Reputation: 87

writing to multiple files at a time

I want to create multiple files inside a loop and write something into them. I have made the following code. But it only creates one file named '1' instead of five files (from 1 to 5):

#include <fstream>
#include<iostream>
using namespace std;
int main(){
  FILE *fp;
  ofstream os;
  char i;
  char fileName[] = "0.txt";
  for(i='1';i<='5';i++)
  {
     fileName[0]=i;
     .
     os.open (fileName);
     os<<"Hello"<<"\n";
  }
}

Is there anything wrong in the code? How will I get the five files?

Upvotes: 0

Views: 4981

Answers (2)

Hatted Rooster
Hatted Rooster

Reputation: 36463

The reference for std::ofstream::open specifically states:

Open file Opens the file identified by argument filename, associating it with the stream object, so that input/output operations are performed on its content. Argument mode specifies the opening mode.

If the stream is already associated with a file (i.e., it is already open), calling this function fails.

You never close the file you're working with in your loop so open for the second-fifth time fails.

add it:

  for(i='1';i<='5';i++)
  {
     fileName[0]=i;
     os.open (fileName);
     os<<"Hello"<<"\n";
     os.close();
  }

Also, you should check if open() succeeded:

  for(i='1';i<='5';i++)
  {
     fileName[0]=i;
     os.open (fileName);
     if(os) // checks if open() succeeeded
     {
       os<<"Hello"<<"\n";
       os.close();
     }
  }

Upvotes: 2

agg3l
agg3l

Reputation: 1444

#include <fstream>
#include <iostream>

using namespace std;

int main() {
  ofstream os;
  char fileName[] = "0.txt";
  for(int i = '1'; i <= '5'; i++)
  {
     fileName[0] = i;
     os.open(fileName);
     os << "Hello" << "\n";
     os.close();
  }
}

Upvotes: 0

Related Questions