This looks like it is something which can be handled in a POSIX environment, so I took a chance and moved the thread to "
Platform/API C++"
Now you want to parse arguments to your program.. there are different ways to handle that, if you want it to be ANSI/ISO compliant, then you need to loop through argv[] from 1 to (argc -1) looking for your desired flag, and shift every following items so you'd end up with an argv[] which only holds the users file-names...
However, here comes the POSIX part in, theres a very userfriendly function called
getopt() And you'd use it in a way like this:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
char opt; /* this will hold the return value from optind */
int count=1, j, i; /* as default we create one file */
while( (opt = (char)getopt(argc, argv, "n:h")) > 0)
{
switch (opt)
{
case 'n':
/* this will be the copies of filename created */
count = atoi(optarg);
break;
case 'h':
printf("Usage: %s [-n <count>] [filename filename ... filename]\n",
argv[0]);
return 0;
}
}
/* at this point the provided optind from getopt()
* will point somewhere in argv[], we need to cover
* every position it might have
*/
/* if we're in luck it is pointing at the beginning */
if(optind == 3){
/* assume the remaining arguments are "filename" qualifiers */
for(i=optind; i < argc; ++i)
for(j=1; j <= count; ++j)
printf("Creating file: %s-%d\n", argv[i], j);
}
else
if(optind == argc || optind > argc){
/* it was given as the very last argument so correct that */
for(i=1; i < (argc -2); ++i)
for(j=1; j <= count; ++j)
printf("Creating file: %s-%d\n", argv[i], j);
}
else
if(optind > 1 && optind < argc){
/* it must've been given somewhere in the mittle (worst case) */
for(i=1; i < (optind - 2); ++i)
for(j=1; j <= count; ++j)
printf("Creating file: %s-%d\n", argv[i], j);
for(i+=2; i < argc; ++i)
for(j=1; j <= count; ++j)
printf("Creating file: %s-%d\n", argv[i], j);
}
else{
/* was only called with filename */
for(i=1; i < argc; ++i)
printf("Creating file: %s\n", argv[i]);
}
return 0;
} Now if we remain in the POSIX world, theres a
access() function, which can tell you if the file exists, and a number of other things, this might lighten your load with the fopen()/fread() thingy to check for an existing file...
ie:
Code:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
int i;
for(i=1; i < argc; ++i)
if(!access(argv[i], F_OK))
printf("File exist: %s\n", argv[i]);
else
printf("File dosn't exist: %s\n", argv[i]);
return 0;
} Hope this sheds some light onto your frustration...