C command line password
So I'm trying to create a C program where you must input the password on the command line, like ./login password1 And if the password is password1, it'll say something. If not, it prints another message. This is the code I have now:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{开发者_开发百科
if (argc < 2) {
printf("usage: %s <password>\n", argv[0]);
}
char pass = "password";
if (argc == pass) {
printf("Right\n");
} else {
printf("Wrong\n");
}
}
But it wont work.
char pass = "password";
You're trying to assign a string to a char
. That won't work! Instead, you need need to declare pass
as a char[]
like this:
char pass[] = "password";
Next problem:
if(argc == pass)
argc
is the number of command line arguments passed to your program (including the program name as the first). What you want is argv
, which contains the actual arguments. Specifically, you probably want argv[1]
.
You can't just go argv[1] == pass
as that compares the location of the two strings. To compare strings, you need to use strcmp()
. This function compares two strings and returns 0 if they're equal (there's good reason for that, but leave it for now). The former is like comparing two houses by checking if they have exactly the same street address; the latter is like comparing the houses with each other brick-by-brick. (sniped from @caf)
So the line becomes:
if (strcmp(argv[1], pass) == 0)
Put those fixes together and it should work. Please also work on improving the indentation of your code. It'll make it much easier to read, not only for others but yourself in a few weeks time.
You're comparing argc
- the count of command line arguments - with the "password"
string pointer.
For a start, you need to use argv[1]
instead of argc
. You also need to use a suitable strcmp
function rather than just comparing the pointers.
Finally, inputting passwords via the command line is usually a bad idea due to security considerations. On many systems the command line may be visible to other users (eg via the "ps" command).
精彩评论