Reputation: 9
I am new to programming and i have a problem where i u se and i need to make many files to write in >15 so i dont whant to do it manualy i used array of files. That works fine but the problem starts when i need to give a location of every file and by using a "for cyclus" i cant change the names of files in destinations here is part of code...
#include <stdio.h>
main()
{
int i;
FILE *files[14];
for(i=0;i<15;i++)
files[i]=fopen("C:\\File.txt" ,"w");
}
for(i=0;i<15;i++)
fclose(files[i]);
getch();
}
problem is with fopen function because it opens only 1st file, but not others... if u need some more explaining please ask will try to provede as much as possible.. thanks
Upvotes: 1
Views: 61
Reputation: 490488
You're only supplying one name, so instead of trying to open 15 files, you're trying to open one file 15 times. Unless you specify a sharing mode, that will fail (at least with most compilers on Windows, which seems to be what you're using).
My guess is you want to open 15 different files though, in which case you need to specify 15 different file names. One possibility for doing that is to synthesize names that include the index. Since you appear to be using C (despite the c++
tag) I'll stick to C for the moment.
int i;
FILE *f[15];
for (i=0; i<15; i++) {
char name[32];
sprintf(name, "File%d.txt", i);
f[i] = fopen(name, "w");
}
Upvotes: 1
Reputation: 881
What you need to do is to first define what array of files you will be using.
So when you declare FILE *files[14], you need to actually specify what each of those files are.
You should first declare a set of strings instead with the specific filenames, and loop over them.
Also, your for loops are wrong, it should be
for(i = 0; i < 14; i++) {
...
}
You need to start indexing at 0, and stop indexing at 13.
Upvotes: 0