Fopen in a for

Hi there, i'm trying to generate some .txt files through a for but i have some problems doing that-
1
2
3
4
5
int i;
for(i=0; i<10; i++) {
        FILE *t[i]=fopen("file[i].txt","w");
        fprintf (t[i],"%s\n%s\n%s",string1[i],string2[i],string3[i]); fclose(t[i]);     
        }

Some advices please?
Last edited on
some problems

What problems?

You are opening the same file over and over again.
FILE *t[i]=fopen("file[i].txt","w");
I know that this isn't good - file[i].txt, what's the correct way?
And also at the compile process i have 1error-
variable-sized object 't' may not be initialized
This is probably what you want
1
2
3
4
5
6
7
8
int i;
char fn[100];
for(i=0; i<10; i++) {
sprintf(fn, "file[%d].txt", i); // This generates the different filenames
        FILE *t=fopen(fn,"w"); // No array needed
        fprintf (t,"%s\n%s\n%s",string1[i],string2[i],string3[i]); fclose(t[i]);     // What is this string1 (etc) if it is std::string you need string1[i].c_str()
flclose(t); // Better close it here
        }
Last edited on
Here a way to do it with streams.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <vector>
#include <string>
#include <fstream>
#include <strstream>

int main(void)
{
	std::vector<std::string> string1(10);
	std::vector<std::string> string2(10);
	std::vector<std::string> string3(10);

	for ( int i = 0; i < 10; ++i )
	{
		std::strstream s;
		s << "d:\\tmp\\file" << i << ".txt" << '\0';
		std::ofstream os( s.str() );
		os << string1[i] << string2[i] << string3[i];
	}

	return 0;
}

Doing the stuff with FILE* is the C style of doing things. In C++ streams are more adequate, because they are extensible. Working with them makes the world a lot more typesafe.
Thank you guys!
Topic archived. No new replies allowed.