Link to home
Start Free TrialLog in
Avatar of tsurai
tsuraiFlag for United States of America

asked on

Storing argv as Variable

How can I pass the contents of argv into a variable?

For instance, I want the user to use a filename as the arg...  so argv would be equal to file.txt.  I want to take that "file.txt" and store it as the variable "infile".
Avatar of Anthony2000
Anthony2000
Flag of United States of America image


you can do the following:

int main(int argc, char * argv[])
{
   char fileName[128];

   if(argc >= 2)
   {
      strncpy(fileName, argv[1], sizeof(fileName)-1);
      fileName[sizeof(fileName)-1] = 0
   }
   else
   {
        // print message telling user to add in the filename
   }



I should have used infile instead of fileName. Sorry.
ASKER CERTIFIED SOLUTION
Avatar of Anthony2000
Anthony2000
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Infinity08
       #include <stdio.h>
       
        int main(int argc, char **argv) {
            char *infile = "";
            if (argc > 1) {
                infile = (char*) calloc(strlen(argv[1]) + 1, sizeof(char));
                strcpy(infile, argv[1]);
            }
            printf("the filename : %s\n", infile);
            return 0;
        }


compile and run like this :

        app file.txt

and the output should be :

        the filename : file.txt
And, of course, if you intend to do more with the application, you need to add a free(infile) as soon as you don't need the filename any more ;)
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial