How to pass commandline argument as part of a string parameter - c

This is part of the code I'm facing issue with :
void encrypt(const char *fileIn, const char *fileOut, const unsigned char *key);
int main(int argc, char *argv[])
{
const unsigned char key[100];
srand(time(NULL));
aes_init();
encrypt(argv[1], "/home/python/encrypt/"argv[1]".encrypted", argv[3]);
return 0;
}
As you can see, in the encrypt function, I'm asking the user to enter the file name via command line for input. For output of the same function, I wanted the same name to be just appended by '.encrypted'. However, I get the following error whenever I try to compile the code.
In function ‘main’:
error: expected ‘)’ before ‘argv’
error: too few arguments to function ‘encrypt’
note: declared here
What am I doing wrong? Please help.

I think you want something easy string manipulation like this
snprintf(key,100,"/home/python/encrypt/%s.encrypted",argv[1]);
encrypt(argv[1],key, argv[3]);

in C, string manipulation is not as smooth as in modern languages. You have to append strings by using library functions.
char buffer[CCHMAXPATH];
sprintf(buffer, "/home/%s.encrypted", argv[1]);
encrypt(argv[1], buffer, argv[3]);

Related

Can't accept multiple command line arguments and assign to variable

I am learning C and I am not used to pointers and the way C handles strings. I am trying to create a program that accepts multiple command line arguments and assigns them to variables so that I can later use them. I can get the program to accept the first argument and assign it as a int. But when I try to accept the second argument I get a SEGMENTATION FAULT. I have tried testing by removing the second variable (service) and then assigning port to argv[2] and it doesn't work. It is something about accepting the second argument that the compiler does not like but I am not able to figure it out.
#include <stdio.h>
int main(int argc, char *argv[]) {
int port = atoi(argv[1]);
char service = argv[2];
return 0;
}
When you write char service = argv[2];, you are assigning a char pointer to a char. You know argv is a char pointer array, because you define it as char *argv[]. Fix by just adding char *service = argv[2];
So your rewritten code could look like this:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc < 3) {
printf("Requires more arguments");
return 1;
}
int port = atoi(argv[1]);
char *service = argv[2];
printf("%s", service); //From edit
return 0;
}
You may want to add a check for the value of argc (i.e. argc >= 3), since it will seg fault if there aren't three arguments.
Edit (response to comment):
To print the service, use:
printf("%s", service);
The %s specifies you will print a string of characters (char *) and you simply use service, because you need to specify the pointer.
Edit 2:
If you don't add #include <stdlib.h>, you will receive something along the lines of "warning: implicit declaration of 'atoi' is invalid in C99", which may also produce an error depending on your compiler settings.

Char (single letter) must be a pointer to correctly work?

I've searched and maybe this is not even an issue but while working with chars in C (I'm working with X-Code on Mac) I'm having problems dealing with them unless I used pointers
int main(int argc, const char * argv[]){
char myChar = "A";
print("%c\n",myChar);
print("%d\n",myChar);
print("%c\n",65);
print("%c\n",74);
return 0;
}
So, simple stuff, but here's the output:
>J
>74
>A
>J
As you see, when I print myChar using %c, it gives me the lettre J and not A, same thing when I use %d, gives me 74 (char code for J) and not 65.
I also have a warning message on my variable declaration :
Incompatible pointer to integer conversion initializing char with an expression of type char[2]"
Which is kind of weird.
Now when replacing my code with this one :
int main(int argc, const char * argv[]){
char *myChar = "A";
print("%c\n",*myChar);
print("%d\n",*myChar);
print("%c\n",65);
print("%c\n",74);
return 0;
}
The output is as expected :
>A
>65
>A
>J
Any idea on what this behavior is due? Did I miss something or do I fail to understand something?
In your code,
char myChar = "A";
is not correct. "A" is a string literal, which is not a fit for a char. You may want to write
char myChar = 'A';
instead.
Note: Enable compiler warnings and pay heed to them.

C convert const char * to char

I searched quite a while to find the answer, but I could only find a solution for C++ that didn't seem to work for C. I'm trying to convert argument of const char * to char to use in my switch statement. I tried various things like strdup(), but was unsuccessful.
#include <stdio.h>
int main(int argc, const char *argv[]) {
char argOne = argv[1];
char argTwo = argv[2];
switch(argOne) {
case '1234' :
printf("1234!\n" );
break;
default :
printf("Invalid\n" );
}
}
While compilation:
warning: incompatible pointer to integer conversion initializing 'char' with an expression of type 'const char *' [-Wint-conversion]
char argOne = argv[1];
^ ~~~~~~~
warning: overflow converting case value to switch condition type (825373492 to 52) [-Wswitch]
case '1234' :
^
In your code,
Point 1:
char argOne = argv[1];
is very wrong. You cannot put a const char * (pointer) to a char variable.
Point 2:
case '1234'
also wrong. Here, the '1234' does not denote a string. It is a multibyte charcater, which is most probably something you don't want. Again, even you change that to something like "1234", still it would be incorrect, as it will not give you the intended value, and strings cannot be used for case statement values.
Solution: Instead of using the switch case here, you can try using strcmp() to compare the incoming string and chose accordingly.
Note: The recommended signature of main() is int main(int argc, char *argv[])
You're getting mixed up between char (character) and char * (string). Also you can not use strings as switch/case labels. Here is a fixed version of your code:
#include <stdio.h>
int main(int argc, const char *argv[]) {
const char *argOne = argv[1];
const char *argTwo = argv[2];
if (strcmp(argOne, "1234) == 0)
{
printf("1234!\n");
}
else
{
printf("Invalid\n");
}
return 0;
}
First of all the standard declaration of main looks like
int main(int argc, char *argv[])
^^^^^^
That is the second parameter does not have qualifier const.
Secondly argv[1] has type char *. There is no any sense to compare it with a character literal similar to '1234'. As for string literal "1234" when it may not be used in the case label.
What you want is the following
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
if ( argc > 2 )
{
char *argOne = argv[1];
char *argTwo = argv[2];
if ( strcmp( argOne, "1234" ) == 0 )
{
puts( "1234!" );
}
else
{
puts( "Invalid" );
}
}
}
You can't (really) "convert" a pointer to char to a single char. You can however extract one single character from a string.
For example, to get the first character of the first argument to your program, you can do e.g.
char first_char_of_first_arg = 0;
if (argv > 1)
first_char_of_first_arg = argv[1][0];
the code contains several problems
compiling with all warnings enabled would allow the compiler to
display those problems.
for gcc, at a minimum, use: '-Wall -Wextra -pedantic'
Note: warnings need to be fixed, as the compiler knows the C language better than you or I.
#include <stdio.h>
int main(int argc, const char *argv[])
{
//<< parameter argc not used
// and it should be used to assure that argv[1] and argv[2] actually exist
char argOne = argv[1];
//<< argv[1] is a pointer to a character string.
// argOne is a single char
// it should be: 'char argOne = argv[0][0];'
char argTwo = argv[2];
//<< argv[2] is a pointer to a character string.
// argTwo is a single character
// it should be: 'char argTwo = argv[1][0];'
//<< argTwo is not used
switch(argOne)
//<< a character can be treated as an int, but due care needs to be exercised
{
case '1234' :
//<< a case statement can only look at an 'int',
// not a pointer to a (in this case unterminated) string
// and argOne is a single char, not a pointer to a unterminated string
printf("1234!\n" );
break;
default :
printf("Invalid\n" );
//<< for human readability, use consistent indentation
// and never use tabs for indenting
//<< every case should be terminated with 'break;'
// unless the case is to fall through to the next case
// I.E. just because a syntax 'can' be used does not mean it 'should' be used
}
}

how to put char * argv[] to global variable

I am just trying to write something like that:
u64 get_env(char *argv[]);
char* g_argv[];
static char * Sample ()
{
return (char*)get_env(g_argv);
}
int main(int argc, char *argv[])
{
g_argv = argv;
Sample();
}
Getting error: 'g_argv' has an incomplete type
warning: array 'g_argv' assumed to have one element [enabled by default]
I've tried many different ways. How to write it right?
The compiler sees you declaring g_argv as an array of char pointers, but you don't specify how many.
int main(int argc, char *argv[])
Despite what it looks like, argv is not an array; arrays aren't first class objects in C and cannot be passed to functions, only their addresses can. So because argv is a parameter, it's actually a pointer to a pointer. For this reason I think it's better to tell the truth and use
int main(int argc, char** argv)
which is exactly equivalent to the above. This confusion in the language has led you to
char* g_argv[];
You're saying this is an array of pointers, without saying how big the array is, but that's not what you want; you want a pointer to the first of several pointers:
char** g_argv;
That fixes the problem you asked about, but I wonder about this declaration:
u64 get_env(char *argv[]);
Why declare it as returning u64 when the name and usage clearly indicate that it returns a char*? Actually, you should not be declaring it here at all ... it should be declared in a header file that specifies the API that includes get_env. Hopefully that header file declares it as returning a char*, and then you can remove the cast from
return (char*)get_env(g_argv);

How to handle data types?

I'm really facing a problem with data types conversions.
I'm making a GUI version of a program with GTK. To get entry_text string I need a const char* which obliges me to use this data type in the function below.
I want to convert it to string(char[]) and compiler keep giving me errors below :
Source code where errors come:
//....
char ret (const char *bd){
char c[100];
strcpy(c,bd);
return *c;
}
char encode(const char ebuf[],const char epass[]) {
char *buf=ret(ebuf);
char *pass=ret(epass);
//...
When I compile the code I get following errors (with g++):
codgui.cpp: In function ‘char encode(const char*, const char*)’:
codgui.cpp:36: error: invalid conversion from ‘char’ to ‘char*’
codgui.cpp:37: error: invalid conversion from ‘char’ to ‘char*’
Anyone have any clue on how to fix this?
Your ret function is only returning the first character in the local variable c. You want to return a char*, and you should never return the address of a local variable, so you will need to create it on the heap.
char* ret (const char *bd){
char *c = new char[100];
strcpy(c,bd);
return c;
}
char encode(const char ebuf[],const char epass[]) {
char *buf=ret(ebuf);
char *pass=ret(epass);

Resources