If you don't want to run into a buffer problem, you need to turn towards something like dynamic memory allocation with the use of
malloc()...
Now I don't want to provide you with the actual program, but in this case I would advice you to split it up, say create a seperate function, where you've actualy create the file ie:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
/* predefine the file-creation function, so we know it exist,
* when refferencing to it from main()
*/
int create_file(char* filename, int count);
int main(int argc, char* argv[])
{
/* this is the main function in my example with getopt()
* in this one every instance of:
* for(j=1; j < count; ++j)
* printf("Creating file: ...");
* is exchanged with:
* create_file(argv[i], count);
*/
}
/* this is the actual body of the create_file(),
* This will create a files by the name: filename-n
* for n in {1, 2, ..., count}
*/
int create_file(char* filename, int count)
{
char* buff; /* our filename with dynamic memory allocation */
/* how long will our char* need to be */
int length = strlen(filename)+3; /* add room for '-' and '\0' */
int i,n=count;
/* deside length */
while(n >= 10){
length++;
n=n/10;
}
/* allocate needed memory for filename-count */
if(!(buff = (char*) malloc(sizeof(char*)*length)))
return -1; /* error allocating memory */
for(i=1; i <= count; ++i){
snprintf(buff, length, "%s-%d", filename, i);
if(!access(buff, F_OK))
printf("Error file: %s exist\n", buff);
else
printf("Creating file: %s\n", buff);
}
free(buff); /* make sure we dont hogg unneeded memory */
return 0;
} I hope I didn't provide you with too much help.. Since I like for you to figure out how this thing actualy should work by yourself..
Naturaly I could have said..
malloc() is used in a way like:
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* buff;
int length=1337;
if(!(buff = (char*) malloc(sizeof(char*)*length))){
printf("Error allocating memory on the heap\n");
return -1;
}
else
printf("Success in allocating memory on the heap\n");
free(buff);
return 0;
} And then tell you to figure out how to use it in your program...
But then again, I wouldn't be encurraging you to make a reasonable design in your program, so you wont end up with a main() function which is thousands of lines long...
But as an exercise I've left the part of combining the example for getopt() with this small example...