I am learning C language. Here is a simple program I did to create 1000 text files.
#include <stdio.h>
#include <string.h>
char * create_filename(char *, char *, int);
int main(void)
{
char prefix_name[50] = "file_no_";
char snum[5];
int no_of_files = 1000;
FILE * fp = NULL;
for (int i = 0; i < no_of_files; i++)
{
fp = fopen( create_filename(prefix_name, snum, i + 1), "w");
fprintf(fp, "This is file no %d", i+1);
fclose(fp);
fp = NULL;
strcpy(prefix_name, "file_no_");
}
return 0;
}
char * create_filename(char * prefix_name, char * snum, int i)
{
sprintf(snum, "%d", i);
strcat(prefix_name, snum);
strcat(prefix_name, ".txt");
return prefix_name;
}
This runs as expected. But I want to know, how can I make this more efficient and as portable as possible. If I want to scale this up to, say 10000 text files, are there other approaches which will be better ?
Thanks