Create a file

hello! i am beginner in C++.com. i want to create a file by C++ but not understand function fstream and ifstream library.
this code is write by me, everybody looking and editing to active.
void createFile(int t)
{
int i, j, x, n = 30000;
char s[10];
char nameFile[20];
for(i = 0; i < t; ++i)
{
itoa(i, s, 10);
strcpy(nameFile, "D:\\data");
strcat(nameFile, s);
strcat(nameFile, ".txt");
fstream file;
file.open(nameFile, ios::in | ios::out);
for(j = 0; j < n; ++j)
{
file<<rand()%n + 1<<endl;
}
file.close();
}
}

thanks
Last edited on
You're opening the file each iteration of the loop, wich isn't very efficentic. And you can create a ifstream-file, for input, and a ofstream-file, for output. You should keep those seperated.
You're code isn't very clear, so I can't help you much further. I would recommend to use c++-style strings, instead of char[].

http://www.cplusplus.com/doc/tutorial/files.html
Last edited on
thanks Scipio!!
I edited content of code. Can you see and reply to me!!
i use style char nameFile[20] to store value name File. When open file, i don't input name file, on the contrary, i want input name file automatic. it most convenient when i want create a lot of files. at the same time, I want input data into file but still not make.
Let me show how it's done with an example. We have an array of thousand integers, "value[]". I'll use two functions, write() to write the data to the file and read() to read the data from the file. Name of the file is "allValues.txt"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

//write to a file:
void write()
{
ofstream out; //declare out of type ofstream
out.open("allValues.txt"); //open file
for (int i=0;i<1000;i++)
{
out<<value[i]<<endl; //write data to the file, using the normal i/o-operations
}
out.close(); //close the file
}

//read from a file:
void read()
{
ifstream in; //declare in of type ifstream
in.open("allValues.txt"); //open file
for (int i=0;i<1000;i++)
{
in>>value[i]; //read data into the integers using normal i/o-operations
}
in.close(); //close file
}


Notice that I use ifstream and ofstream, not fstream.

If you need any more explanation about filestreams:
http://www.cplusplus.com/doc/tutorial/files.html
http://www.cplusplus.com/reference/iostream/fstream/

If this doesn't solve your problem, I don't understand your question right.
thank you!!!
I tested it. it active normal. now, I understanded way solve this problem.
Topic archived. No new replies allowed.