1

I want to create some text file in C++. For example: I will run a loop from 1 to 5 and create the following files:

1.txt
2.txt
3.txt
4.txt
5.txt

is it possible? I have made a sample code:

#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;

main()
{
   FILE *fp;
    int i;
    for(i=1;i<=5;i++)
    {
        //fp=fopen("%d.txt","r",i); //what will go here??

 }
}

I am confused about what I will write inside the loop. how can I create those files?

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
AAA
  • 87
  • 3
  • 9

3 Answers3

4
char i;
char fileName[] = "0.txt";
for(i='1';i<='5';i++)
{
   fileName[0]=i;
   fp=fopen(fileName,"r"); //what will go here??
   //...
}

You can use sprintf if this is too simple for your case;


Since you tag c++, I think fstream string is the thing to use.

A simple c++ example

#include <fstream>
#include <string>
using namespace std;

int main(){
   string base(".txt");
   for(int i=1;i<=5;++i){
      ofstream(to_string(i)+base);// to_string() need c++11
   }
}

If you still don't have to_string (you don't have c++11 or your compiler just don't have this) you can use this simple version for now. (better put this in your own namespace)

#include <string>
#include <sstream>

std::string to_string(int i){
   std::stringstream s;
   s << i;
   return s.str();
}
apple apple
  • 10,292
  • 2
  • 16
  • 36
  • This will not behave as asked if i > '9' (since the 1 to 5 part is an example) – sokkyoku Sep 25 '16 at 11:26
  • than use `sprintf` or just use `c++` things, I'm adding them to my answer – apple apple Sep 25 '16 at 11:27
  • I am getting an error saying to_string was not declatred in this scope @apple apple – AAA Sep 25 '16 at 12:27
  • @AAA What compiler are you using and in which standard are you compiling? `to_string()` is defined in ``, but since C++11. – Bob__ Sep 25 '16 at 12:32
  • I am using Code Blocks version 13.12 @Bob__ – AAA Sep 25 '16 at 12:35
  • @AAA It's a bit old. Have you tried to add the option `-std=c++11` to the compiler options? – Bob__ Sep 25 '16 at 12:40
  • I am very new to this. can you please describe the process of adding it? @Bob__ – AAA Sep 25 '16 at 12:48
  • @AAA look at [this](http://stackoverflow.com/questions/18174988/how-can-i-add-c11-support-to-codeblocks-compiler). – Bob__ Sep 25 '16 at 13:01
  • @AAA you can use `to_string` in updated answer, but I would suggest update your compiler. – apple apple Sep 25 '16 at 14:47
  • If I want to write "hello" in each file inside the loop. what I will have to do? @apple apple – AAA Sep 25 '16 at 16:33
  • @AAA I see other of your question, and I think you need to learn the basic of `c++` before asking similar question multiple times, and if you really understand any of your question's answer, you will not have these duplicate question. – apple apple Sep 26 '16 at 13:54
  • @AAA to answer your question, `ofstream file("name"); file<<"hello";` – apple apple Sep 26 '16 at 13:57
2

You can use a std::stringstream to compose the file name before passing it to the std::ofstream constructor as a std::string.

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <iomanip>

int main()
{
    std::cout << "How many files do you want to create? ";
    int n;
    std::cin >> n;

    std::cout << "How many digits do you want to display? ";
    int n_digits;
    std::cin >> n_digits;   // i.e. zeroes == 3  ->  001.txt

    std::cout << "Enter a common prefix for all the files: ";
    std::string prefix;
    std::cin.ignore();
    std::getline(std::cin, prefix);  // i.e. prefix == "file"  -> file001.txt

    std::string ext(".txt");
    for ( int i = 1; i <= n; ++i )
    {   // use a stringstream to create a file names like: prefix001.txt
        std::stringstream ss;
        ss << prefix << std::setfill('0') << std::setw(n_digits) << i << ext;

        // open the file. If not c++11 use  ss.str().c_str()  instead
        std::ofstream file( ss.str() );
        if ( !file )
        {
            std::cerr << "Error: failed to create file " << ss.str() << '\n';
            break;
        }

        // write something to the newly created file
        file << "This is file: " << ss.str() << "\n\nHello!\n";
        if ( !file )
        {
            std::cerr << "Error: failed to write to file " << ss.str() << '\n';
            break;
        }
    }
}
Bob__
  • 12,361
  • 3
  • 28
  • 42
0
#include <iostream>
#include <fstream>

int main(void)
{

    std::ofstream out; // you must call out.close() inside loop to be able to open another file for writting otherwise you'll get only the first one "a.txt"
    std::string sFileName;

    for(char c('a'); c < 'f'; c++)
    {
        sFileName =  c;
        sFileName += ".txt";
        out.open(sFileName.c_str(), std::ios::out);
    //  std::ofstream out(sFileName.c_str(), std::ios::out); // here you are not obliged to call out.close() because the first out is not the very second and so on...
        out.close(); // very important if you use the same ofstream to open another file
    }

    std::cout << std::endl;
    return 0;
}

*** to be able to use one ostream object in opening many files you must close the precedent file to be able to open the next otherwise it fails trying creating the next one.

Raindrop7
  • 3,889
  • 3
  • 16
  • 27