This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 5 years ago.
I recently wrote a brute force program to turn the octal data from permissions in Unix into the human readable form (e.g. 755 -> rwxr-xr-x) However whenever I run my program called myperm I don't get a result (e.g. ./myperm 755 -> nothing) and I'm not quite sure why can anyone help with this
#include <stdio.h>
#include <string.h>
int main (int argc, char *argv[])
{
if (argv[1] == "777")
{
printf("rwxrwxrwx");
}
else if (argv[1] == "755")
{
printf("rwxr-xr-x");
}
else if (argv[1] == "750")
{
printf("rwxr-x---");
}
else if (argv[1] == "700")
{
printf("rwxr-x---");
}
else if (argv[1] == "666")
{
printf("rw-rw-rw");
}
else if (argv[1] == "664")
{
printf("rw-rw-r--");
}
else if (argv[1] == "640")
{
printf("rw-r-----");
}
else if (argv[1] == "600")
{
printf("rw-------");
}
else if (argv[1] == "400")
{
printf("r--------");
}
return (0);
}
Comparing strings in C doesn't work like this, you have to use strcmp
Instead of doing if (argv[1] == "XXX"), you should do if (strcmp(argv[1], "XXX") == 0)
Read on here
argv[1] == "755"
is not how you compare strings in C, you need to use:
strcmp (argv[1], "755") == 0
In any case, this "brute force" method is both totally unnecessary and unreliable (missing possibilities, only nine of the 512 possibilities are handled, even without taking into account setuid and setgid bits and so on).
You would be better off having a function to evaluate one octal digit, such as:
static const char * permXlat (char octal) {
switch (octal) {
case '0' : return "---";
case '1' : return "--x";
case '2' : return "-w-";
case '3' : return "-wx";
case '4' : return "r--";
case '5' : return "r-x";
case '6' : return "rw-";
}
return "rwx";
}
and then processing the argument one character at a time:
printf ("%s%s%s\n",
permXlat (argv[1][0]),
permXlat (argv[1][1]),
permXlat (argv[1][2]));
adding whatever sanity checking you think is necessary (argument list size, character values and so on).
Related
This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 3 years ago.
I was working on a problem where I need to get the birthday of someone and I need to convert the string name of the month into the integer counterpart of it, for example, if the user input "jan", the program must output 1.
I am just a beginner in C so it will be a great help if you give me some enlightenments
here is my code:
#include <stdio.h>
#include <string.h>
void birthconvert(char bm[])
{
if (bm == "jan")
{
printf("01");
}
else if (bm == "feb")
{
printf("02");
}
else if (bm == "mar")
{
printf("03");
}
else if (bm == "apr")
{
printf("04");
}
else if (bm == "may")
{
printf("05");
}
else if (bm == "jun")
{
printf("06");
}
else if (bm == "jul")
{
printf("07");
}
else if (bm == "aug")
{
printf("08");
}
else if (bm == "sep")
{
printf("09");
}
else if (bm == "oct")
{
printf("10");
}
else if (bm == "nov")
{
printf("11");
}
else if (bm == "dec")
{
printf("12");
}
}
int main() {
char birthmonth[3];
printf("Enter your birth month: ");
gets(birthmonth);
birthconvert(birthmonth);
}
You can't use == to test the equality of strings in C.
You have to use a function like strncmp() or strcmp(), which are defined by using man 3 strncpm command on a Linux system.
You also have the documentation here.
Be careful, you also have to include the header <string.h>
What is the proper way to receive a command line argument from the user and compare it to a single char? For example if the user typed "Y" for yes run some function and "N" for no would run another function.
My main error is "comparison between ptr and integer" & "too few arguments to function call, expected 3 have 1"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void calculate();
void verify();
int main (int argc, char *argv[]) {
if(argc < 2){
printf("Please enter a mode of operation.\n");
return 0;
}
else if(argc > 2){
printf("Too many arguments supplied. Please try again.\n");
return 0;
}
else if(strncmp(argv[1] == 'c') == 0)
calculate();
else if(strncmp(argv[1] == 'v') == 0)
verify();
return 0;
}
void calculate(){
}
void verify(){
}
You're not calling strncmp() correctly. It should be:
strncmp(argv[1], "c", 1)
It takes 3 arguments: two strings and a limit. 'c' is a char, not a string, string literals are put in double quotes.
You can also write simply:
if (argv[1][0] == 'c')
This just checks the first character, so the user can type y or yes and they'll match y. If you want to match the whole argument and require it be just a single character, you should use strcmp() rather than strncmp():
if (strcmp(argv[1], "c") == 0)
This
strncmp(argv[1] == 'c') == 0
just is incorrect syntax. For starters the function strncmp requires three arguments and it deals with strings while in the avove call of the function there is supplied only one argument of type int. because the wrong expression argv[1] == 'c' has type int and is equal to 0.
I can suggest the following solution
else if ( argc > 2 || strlen( argv[1] ) != 1 ){
printf("Too many arguments supplied. Please try again.\n");
return 0;
}
else if ( argv[1][0] == 'c' )
calculateCRC();
else if ( argv[1][0] == 'v' )
verifyCRC();
This question already has answers here:
How to compare strings in an "if" statement? [duplicate]
(5 answers)
Closed 8 years ago.
I am running this program with with ./crack 50yoN9fp966dU
50yoN9fp966dU is crimson encrypted. which is on the word list. My program is as follow:
#define _XOPEN_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if(argc > 2)
{
printf("Invalid Argument \n");
return 1;
}
else
{
FILE *fp1;
fp1 = fopen("/usr/share/dict/words", "r");
char line[9];
while (fgets(line, 9, fp1) != NULL)
{
char *EncryptLine1;
char *EncryptLine2;
printf("%s", line);
EncryptLine1 = crypt(line, "50");
if(argv[1] == EncryptLine1)
{
printf("%s \n", line);
}
EncryptLine2 = crypt(line, "HA");
if(argv[1] == EncryptLine2)
{
printf("%s \n", EncryptLine2);
}
}
}
}
If I add a printf("%s", EncryptLine1), I see the argv[1], i.e 50yoN9fp966dU, but the loop continue and does not print the answer.
You are doing pointer comparison instead of contents (pointed data) comparison.
Change this:
if (argv[1] == EncryptLine1)
To this:
if (strcmp(argv[1],EncryptLine1) == 0)
And this:
if (argv[1] == EncryptLine2)
To this:
if (strcmp(argv[1],EncryptLine2) == 0)
You have some problems in your code:
You blithely assume argc will never be smaller than 2. Check for unequal 2 instead of bigger two in your first condition.
Anyway, if you return out of an if-block, using else and doing deeper nesting is really superfluous.
Strings cannot be compared with ==, use strcmp.:
if( ! strcmp(argv[1], EncryptLine1))
You need to add a break to break out of the loop or a return to leave the function in your conditional block after printing success, if you want to end the loop there.
if( ! strcmp(argv[1], EncryptLine1)) {
printf("%s \n", line);
break;
}
BTW: Why don't you reuse EncryptLine1 (not that you need any temporary at all there)?
argv[1], EncryptLine1 and EncryptLine2 are all char*s. operator== on two char*s simply checks to see if they are pointing to the same memory location. What you want is to compare the contents of the strings they represent. So, the ifs should look like this:
if(!strcmp(argv[1], EncryptLine1))
I'm having trouble using strcmp in C.
I'm trying to compare a program's arguments using strcmp but even though the strings are the same it doesn't work. Here is the portion of code.
while(strcmp(argv[i], "-e") != 0)
So for i = 11 if I print the value of argv[i] I get
printf("String %s i %d", argv[i],i);
>> String -e i 11
But the while keeps on going. Any ideas why this is happening?
Code:
while(strcmp(argv[i], "-e") != 0 || i != argc)
{
printf("String %s i %d", argv[i],i);
if(!isdigit((unsigned char)*argv[i]) && strcmp(argv[i], "-t") != 0)
{
archivo = fopen(argv[i] , "r");
TOT_IMG = TOT_IMG + 1;
for(t=0;t<NUM_FUNC_TRAZO;t++)
{
for(d=0;d<NUM_FUNC_DIAMETRICA;d++)
{
for(c=0;c<NUM_FUNC_CIRCO;c++)
{
if (fscanf(archivo, "%s",el) != EOF)
{
par->vector_circo[t][d][c] = strtod(el,NULL);
par->clase = clase;
}
else
{
break;
}
}
}
}
par_temp = par;
par->siguiente = (parametros_lista) malloc(sizeof(parametros_elem));
par = par->siguiente;
par->anterior = par_temp;
}
else
{
if(strcmp(argv[i], "-t") != 0)
{
clase = atoi(argv[i]);
CLASES = CLASES + 1;
}
}
i = i + 1;
}
Let's look at this:
while(strcmp(argv[i], "-e") != 0 || i != argc)
OK, so let's assume strcmp correctly returns 0 when argv[i] is "e". We'll assume this because it's exceedingly unlikely that there's a bug in your library implementation of strcmp.
What happens if strcmp returns 0? Well, things don't just stop, your code checks whether i != argc is true. Is it? My psychic debugging skills tell me that you should look into that second part of the while.
You may also want to note that it's possible that your code could, potentially, access argv[argc], which is NULL. You may get lucky if strcmp is lenient when the input is NULL, but it's a bug that you should fix.
I'd rather recommend you to use getopt (3). This is widely used approach to parameters parsing conforming with POSIX.
Also there was another question related to achieving getopt.h interface on windows: getopt.h: Compiling UNIX C-Code in Windows. What's important it is answered (Xgetopt) so portability should be not a case.
Why is my code under giving me back "Not a valid command" when i give the argument print ?
int main(int argc, char *argv[]) {
printf("Argument 2 er %s\n", argv[1]);
if(argv[1] == "print") {
printf("Print kommando kalt");
} else if(argv[1] == "random") {
printf("Random kommando kalt");
} else if(argv[1] == "replace") {
printf("Replace kommando kalt");
} else if(argv[1] == "remove") {
printf("Remove kommando kalt");
} else if(argv[1] == "len") {
printf("øem kommando kalt");
} else {
printf("Ingen gyldig kommando\n");
}
}
You cannot compare C strings using ==. This only does a pointer comparison. You need to use strcmp instead:
if (strcmp(argv[1], "print") == 0) …
Because you cannot compare strings like that in C.
You need to use:
if(strcmp(argv[1], "print") == 0)
printf("Print kommando kalt\n");
And so on.
Also, make sure you don't access argv[1] without making sure it's really there and valid; if your program gets called with no arguments it will be NULL. You can use the value of argc to determine how many arguments you got.
Because argv[1] is a char*: something like 0xDEADBEEF
and "print" behaves as if it is another char*: something like 0xBADF00D
and 0xDEADBEEF != 0xBADF00D
You want to use strcmp() ( http://linux.die.net/man/3/strcmp )