making a lot of files using the fstream

Started by
1 comment, last by Enigma 18 years, 7 months ago
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
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.
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:
// snprintfchar 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);}// streamsstd::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

This topic is closed to new replies.

Advertisement