Reputation: 131
I'm creating a very simple C program call open.c
that will either:
1) List the files in the directory that will have the files text stored in an array
I have this code so far but it doesn't seem to work.
{ }
Upvotes: 0
Views: 217
Reputation: 32953
The way you are trying to read command line arguments is wrong
Given
int main(int argc, const char * argv[])
the first argument to your program (eg "-ad") will get stored in argv[1]
. You need to analyze that string to know what your program is expected to do.
Here's a basic intro to argc and argv. In real world programs there should be some protection as well: for example, the program should check whether it was actually called with a parameter by checking argc:
if (argc < 2) {
printf("What do you want me to do?\n");
return 3;
}
Alternatively - but try to get it working by handling the command line arguments manually at least once - you could delegate the entire command line handling to getopt.
Upvotes: 2
Reputation: 23699
You need to use argv
to compare the command-line arguments with "-ah"
and "-ad"
.
#include <string.h>
if (argc > 2)
{
if (strcmp (argv[1], "-ah") == 0)
{
/* List hidden files */
}
else if (strcmp (argv[1], "-ad") == 0)
{
/* List files */
}
else
{
/* Unknown command-line argument */
}
}
else
{
/* No command-line arguments */
}
References:
C11 (n1570), § 5.1.2.2.1 Program startup
If they are declared, the parameters to the
main
function shall obey the following constraints:— The value of
argc
shall be nonnegative.—
argv[argc]
shall be a null pointer.— If the value of argc is greater than zero, the array members
argv[0]
throughargv[argc-1]
inclusive shall contain pointers to strings, which are given implementation-defined values by the host environment prior to program startup. The intent is to supply to the program information determined prior to program startup from elsewhere in the hosted environment. If the host environment is not capable of supplying strings with letters in both uppercase and lowercase, the implementation shall ensure that the strings are received in lowercase.— If the value of argc is greater than zero, the string pointed to by
argv[0]
represents the program name;argv[0][0]
shall be the null character if the program name is not available from the host environment. If the value of argc is greater than one, the strings pointed to byargv[1]
throughargv[argc-1]
represent the program parameters.
Upvotes: 3
Reputation: 64298
Instead of
if (-ad)
you have to write something like
if (strcmp(argv[1],"-ad")==0)
Same for if (-ah)
Upvotes: 2