How can I pass argument from cmd which is equal to the name of the file I want to open with other function than main?
I want to run program in cmd as "myprogram -open myfile.txt" just for example, and I want use another function to count characters or spaces or whatever in this file. How can I pass the name of file, which is in this case argv[2] to another function in which I can use fopen? thanks for your time.
int main(int argc, char **argv)
{
if((argc==3) && (strcmp("-open", argv[1]) == 0))
etc.
Simply pass in argv[2]
.
int main(int argc, char **argv)
{
if((argc==3) && (strcmp("-open", argv[1]) == 0))
{
FILE *fp = fopen(argv[2]);
//OR
otherFuncThatCallsFopen(argv[2]);
}
}
argv[2]
is a valid char *
that points to the 2nd argument.
You could write a function with signature like unsigned int count_characters(const char *file_name)
and call it with count_characters(argv[2])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.