We help IT Professionals succeed at work.

Storing argv as Variable

tsurai
tsurai asked
on
486 Views
Last Modified: 2010-04-15
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".
Comment
Watch Question


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.
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
CERTIFIED EXPERT
Top Expert 2009

Commented:
       #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
CERTIFIED EXPERT
Top Expert 2009

Commented:
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 ;)
jkr
CERTIFIED EXPERT
Top Expert 2012
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
ozo
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.