tsurai
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".
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".
I should have used infile instead of fileName. Sorry.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
#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
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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)-
}
else
{
// print message telling user to add in the filename
}