Thanks adak, but it gives the same result as my effort previously. Is very frustrating. Yours does look nicer though!
I will muck around with your version now. maybe I missed something.
Printable View
Thanks adak, but it gives the same result as my effort previously. Is very frustrating. Yours does look nicer though!
I will muck around with your version now. maybe I missed something.
OK, one more time! :)
Output:Code:#include <stdio.h>
#include <string.h>
int main() {
char ch;
char file[12] = {"TomB"};
char newfile[12] = {"\0"};
char ext[5] = {".txt"};
int i = 0, length, j;
FILE *nf;
printf("\n\n");
while(ch = file[i]) {
newfile[0] = ch;
strcat(newfile, ext);
nf = fopen(newfile, "w");
printf("\n%s ", newfile);
if (nf == NULL) {
fprintf(stderr, "Can't open created file %s!\n", newfile);
exit(1);
}
length = strlen(newfile);
for(j = 0; j < length; j++)
newfile[j] = '\0';
++i;
}
j = getchar();
return 0;
}
T.txt
o.txt
m.txt
B.txt
using strcat when you need to update only 1 char... too complicated
something like that should work I supposeCode:char mask[] = "TomB";
char name[] = "1.txt";
size_t len = strlen(mask);
size_t i;
for(i = 0; i< len; i++)
{
FILE* fp;
name[0] = mask[i]; /* see - you just replace 1 char in the name */
fp = fopen (name, "w");
if(fp)
{
printf("File %s opened\n", name);
fclose(fp);
}
}
Why not put the filename generating code into its own function, to simplify things?
Code:char* generate_filename( const char* template_name, int index, const char* extension, char* buffer, int maxlen )
{
char digits[ 32 ];
sprintf( digits, "%d", index );
if( ( int )( strlen( template_name ) + strlen( digits ) + strlen( extension ) + 1 ) > maxlen )
return NULL;
strcpy( buffer, template_name );
strcat( buffer, digits );
strcat( buffer, extension );
return buffer;
}
int main( void )
{
char buffer[ 1024 ];
for( int i = 12; i < 20; i++ )
{
if( generate_filename( "TomB", i, ".txt", buffer, 1024 ) )
{
puts( buffer );
}
else
{
puts( "buffer too small" );
}
}
}
Thank you all for your input, it has given me a lot to think about and to learn. I will try to understand fully what you have all shown.
I will not look into how to consolidate all this and to learn how to actually manipulate the files now.
Thanks again!
:)