请教 c语言中 如何生成多个不同名的文件
#include <stdio.h>
main()
{int n;
char filename[4]={ 'a ', 'b ', 'c ', 'd '};
FILE *fp[4];
for(n=0;n <4;n++)
{
if((fp[n]=fopen(filename[n], "w "))==NULL)
{printf( "cannot open file! ");return;}
fclose(fp[n]);
}
}
我想生成文件名分别为 a.txt b.txt c.txt d.txt的四个文件。但执行的结果是cannot open file!
请教如何才能循环产生多个不同文件名的文件。谢谢!
[解决办法]
char *filename[4]={ "a.txt ", "b.txt ", "c.txt ", "d.txt "};
FILE *fp[4];
for(n=0;n <4;n++)
{
if((fp[n]=fopen(filename[n], "w "))==NULL)
{printf( "cannot open file! ");return;}
fclose(fp[n]);
}
...
[解决办法]
/*自动生成N个文件*/
#include <stdio.h>
#include <stdlib.h>
#include <dir.h>
int main()
{ int Total,I;
char file[10],Path[MAXPATH],File[MAXPATH];
FILE *fp;
printf( "Input the number of files you 'll create! ");
if(scanf( "%d ",&Total))
{ getcwd(Path,MAXPATH);
strcat(Path, "\\NewFile "); /*在当前目录中创建新目录NewFile*/
mkdir(Path);
for(I=1;I <=Total;I++)
{ strcpy(File,Path);
strcat(File, "\\ ");
strcat(File,itoa(I,file,10));
strcat(File, ".txt "); /*文件格式*/
fp=fopen(File, "wt ");
if(!fp) break;
else fclose(fp); /*加上关闭文件一句,防止造成非正常程序中断*/
}
}
if(I> Total) puts( "OK! ");
else puts( "Fail to create all files! ");
getch();
return 0;
}