Jump to content
  • Advertisement
Sign in to follow this  
dk32321

making a lot of files using the fstream

This topic is 4814 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

i am using c++, and using the fstream library, but i am making a for loop to like this for(int i = 0; i < 1000; i++) { textfile.open("txtfile.txt"); } but the problem is it olny creates the file once, i want it where it creates the file 1000 times. if anybody could help me i would appreciate it

Share this post


Link to post
Share on other sites
Advertisement
You are close, but you need to use dynamic file names to actually make new files:

char* baseName = "txtfile";
for(int i = 0; i < 1000; i++)
{
char fileName[256] = {0};
sprintf( fileName, "%s_%i.txt", baseName, i);
textfile.open(fileName);
}


Of course there are more 'safe' methods using stringstream and snprintf, but it's up to you to use them if you want. You have to use unique filenames when you are on Windows.

Share this post


Link to post
Share on other sites
Quote:
Original post by Drew_Benton
Of course there are more 'safe' methods using stringstream and snprintf, but it's up to you to use them if you want.

Please do. There are enough buffer overflow exploits in modern code as it is, without people adding more. And you may say that this is only for your own use, but it's better to learn good practice now than change a habit later. And you may say that since "txtfile_.txt" only has 12 characters and an integer can only have a maximum of 11 characters, so 256 is more than enough space to ensure that a buffer overflow will never occur. But what if you come back to the code a year later and change "txtfile" to something a lot longer? Since the safe code is so trivial to write anyway I would argue that you would be foolish not to use it:
// snprintf
char const * const baseName = "txtfile";
for (int i = 0; i < 1000; ++i)
{
char fileName[256] = {0};
snprintf(fileName, 256, "%s_%i.txt", baseName, i);
textfile.open(fileName);
}

// streams
std::string const baseName("txtfile");
for (int i = 0; i < 1000; ++i)
{
std::ostringstream stream;
stream << baseName << '_' << i << ".txt";
textfile.open(stream.str().c_str());
}

Enigma

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!