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++
code that makes files with sequencial name?
Started by alirezan, Jul 23 2008 10:58 AM
5 replies to this topic
#1
Posted 23 July 2008 - 10:58 AM
|
|
|
#3
Posted 23 July 2008 - 11:10 AM
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:
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 }
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.)
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
Posted 23 July 2008 - 12:16 PM
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
Posted 23 July 2008 - 12:57 PM
Alright! Perfect! It worked!
Thanks
Thanks


Sign In
Create Account


Back to top









