Jump to content

code that makes files with sequencial name?

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
5 replies to this topic

#1
alirezan

alirezan

    Learning Programmer

  • Members
  • PipPipPip
  • 62 posts
Hello,

I want to write a C/C++ code that generates files with names being in a sequence. Like, I want the first one to be f1.txt, the second f2.txt, third be f3.txt ,...

I tried stringstream, I tried casting, I tried all sorts of stuff, but I couldn't do it. Can anybody help me with this please?

Thanks

By the way, I'm using GNU C compiler and g++

#2
Xav

Xav

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 13,118 posts
This should be simple enough. Just a short loop construct, some string concatenation and you're done.
Jordan said:

Good members, like yourself, stick around and post for ages to come!
Mr. Xav | Blog | Forums

#3
alirezan

alirezan

    Learning Programmer

  • Members
  • PipPipPip
  • 62 posts
I did that already but g++ doesn't like string concatenation in filenames I guess.

Maybe I'm doing it wrong, can you please take a look at my code:

Quote

1 #include <fstream>
2 #include <string>
3
4 using namespace std;
5
6 int main()
7 {
8 string fname = "File";
9 string fext = ".txt";
10
11
12
13
14 for (int i=1; i<=10000; i++)
15 for (int j=1; j<23; j++)
16 {
17 fstream file_op(fname + i + fext,ios::out);
18 file_op<<"test! test! test! test! test! test! test! ";
19 }
20 file_op.close();
21 return 0;
22 }


Quote

alirezan@lxb402> g++ -o file_sequence file_sequence.cpp
file_sequence.cpp: In function `int main()':
file_sequence.cpp:17: error: no match for 'operator+' in 'fname + i'
file_sequence.cpp:20: error: `file_op' undeclared (first use this function)
file_sequence.cpp:20: error: (Each undeclared identifier is reported only once
for each function it appears in.)


#4
dcs

dcs

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 775 posts
One way:
#include <iostream>

#include <fstream>

#include <sstream>

#include <string>


using namespace std;


int main()

{

   string fname = "File";

   string fext = ".txt";


   for ( int i = 1; i <= 3; ++i )

   {

      [COLOR="Blue"]ostringstream oss;

      oss << fname << i << fext;[/COLOR]

      cout << oss.str() << '\n';

      fstream file_op([COLOR="Blue"]oss.str().c_str()[/COLOR],ios::out);

      file_op<<"test! test! test! test! test! test! test! ";

   }

   return 0;

} 



#5
alirezan

alirezan

    Learning Programmer

  • Members
  • PipPipPip
  • 62 posts
Alright! Perfect! It worked!

Thanks

#6
Xav

Xav

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 13,118 posts
Good work, dcs. +rep given.
Jordan said:

Good members, like yourself, stick around and post for ages to come!
Mr. Xav | Blog | Forums