Unix environment running C programs - c

I am programming C programs in a Unix environment. I need to take a number from a user before the program is executed like so:
./program.out 60
How do I store the integer value in the C program?

You can use argv[] to get command line parameters, e.g.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int n;
if (argc != 2) // check that we have been passed the correct
{ // number of parameters
fprintf(stderr, "Usage: command param\n");
exit(1);
}
n = atoi(argv[1]); // convert first parameter to int
// ... // do whatever you need to with `n`
return 0;
}

int main (int argc, char *argv [ ])
{
//your code
}
argv [1] will then have the address of the numeric string which contains the number.
Then you can change this to an int if needed.

It is quite simple to do and I hope I have got your question right. See below:
#include <stdio.h>
int main(int argc, char* argv[])
{
printf("Number of arguments is: %d\n", argc);
printf("The entered value is %s\n", argv[1]);
return 0;
}
And then compile it on Linux as:
gcc file.c
./a.out 32
The program should print the value you require.
Hope this helps.

Related

main program that receives arguments, recognizes chars, and verifies if one argument is present

I'm very new to programming and aI would say almost mediocre. I have a program I need to write for school and the First requirements are :
main program must be able to receive a variable amount of arguments from terminal. If no argument is given, program must stop.
main program can recognize the arguments/options "-t,-c,-a,-g" (in no particular order).
main program must make sure that argument -t is present. if it's not, program must stop and print a message asking to provide at least one title (-t is for title).
Here is what I have so far for only the first requirement.
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
void reception_critere(int argc, char * argv[]); //declaration of fct
void reception_critere(int argc, char * argv[]) //definition of fct
{
int i;
// affichage des arguments
printf("Nombre d’arguments passes au programme : %d\n", argc);
for(i = 0 ; i< argc ; i ++) {
printf(" argv[%d] : ‘%s’\n", i, argv[i]);
}
//prg.c
int main (void)
{
reception_critere() //not sure what to put here
return 0 ;
}
They must already be received from the main function.
like this :
int main (int argc, char * argv[])
{
reception_critere(argc, argv);
return 0 ;
}

How to capture the value of export and place it inside my program [duplicate]

I need to know a way for use environment variables in the C programming language. How can I use and read them?
For example, read an environment variable or take the value of an environment variable and load it in another variable.
You can use following functions -
char * getenv (const char *name)-returns a string that is the value of the environment variable name.
char * secure_getenv (const char *name)
Read about some more functions here -http://www.gnu.org/software/libc/manual/html_node/Environment-Access.html#Environment-Access
Use the getenv function from stdlib.h. That's it!
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("test\n");
const char* s = getenv("PATH");
// If the environment variable doesn't exist, it returns NULL
printf("PATH :%s\n", (s != NULL) ? s : "getenv returned NULL");
printf("end test\n");
}
getenv:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char* my_env_var = getenv("MY_ENV_VAR");
if(my_env_var)
printf("Var found: %s", my_env_var );
else
printf("Var not found.");
return 0;
}
On windows, you would use GetEnvironmentVariable.
#include <stdio.h>
#include <winbase.h>
int main(int argc, char *argv[])
{
TCHAR buff[100] = T("");
DWORD resultLengthInCharacters = GetEnvironmentVariable(T("USERDOMAIN"), buff, 100);
if (resultLengthInCharacters > 0 && resultLengthInCharacters < 100) {
_tprintf(T("USERDOMAIN: %s\n"), buff);
} else if ( resultLengthInCharacters > 100) {
_tprintf(T("USERDOMAIN too long to store in buffer of length 100, try again with buffer length %lu\n"), resultLengthInCharacters);
} else {
// Error handling incomplete, should use GetLastError(),
// but typically:
_tprintf(T("USERDOMAIN is empty or not set in the Environment\n"));
}
return 0;
}
But if you are trying to get a standard path variable, you should use the SHGetFolderPath function with the right CSIDL variable (like from this question: How do I get the application data path in Windows using C++?)
Another way could be to use the global variable environ.
#include <stdio.h>
extern char** environ;
void main(int argc, char* argv[])
{
int i=0;
while(environ[i]!=NULL){
printf("%s\n",environ[i++]);
}
}

where to read cmd input like "myapp.exe input" or "myapp.exe -?" (i using cmd)

When I using Java, i need to type command likejava -?If user type -? at the end, why the application know this to reply output? Please tell me c code to identify the -?
They are passed as the parameters to main():
#include <stdio.h>
int main(int argc, const char* argv[])
{
for (int i = 0; i < argc; i++) {
printf("Arg %i is %s\n", i, argv[i]);
}
}
When compiled and then executed as
myProgram.exe arg1 stuff ?
It would output
Arg 0 is myProgram.exe
Arg 1 is arg1
Arg 2 is stuff
Arg 3 is ?
In C you have three options for your main signature. The first is the one that does not take any parameters int main(void). The second one int main() as mentioned in the comments takes any number of parameters but they are unnamed. The third one however has two parameters int main(int argc, char **argv) the names of the parameters do not matter they are just commonly used. These two parameters serve the purpose to provide the command line parameters to your program.
argc: Is the counter variable which holds the number of the provided arguments separated by spaces
argv: contains the command line arguments as an array of c-strings
Your program implicitely receives always one argument which is the name of the application (or \0 if the host environment can not provide that). Here a little example on how to iterate over the arguments:
#include <stdio.h>
int main(int argc, char **argv) {
for(int i = 0; i < argc; i++) {
printf("%s\n", argv[i]);
}
}
In C, the main is declared as:
int main(int argc, char** argv);
the first argument is the number of parameters while the second one is an array of parameters so, for example in your case you would do:
#include<string.h>
#include<stdio.h>
#define QUESTION_MARK "-?"
int main(int argc, char **argv){
if(argc > 1){
char *qsmark = argv[1];
if(strcmp(qsmark, QUESTION_MARK) == 0){
printf("argv[1] is -?\n");
}
}
return 0;
}
Remember that the first argv is the name of the executable.
Please avoid comparing string by hands though, use the standard library to get if what is pointed by qsmark is actually equal to "-?"
If you can use getopt() or other similar POSIX functions. Then this is one way to go:
#include <stdlib.h>
#include <stdio.h>
#include <getopt.h>
int main(int argc, char** argv)
{
int opt;
while ((opt = getopt(argc, argv, "h?")) != -1)
{
switch (opt)
{
case '?':
case 'h':
printf("Usage: bla bla\n");
break;
}
}
return EXIT_SUCCESS;
}
Example:
~ # /tmp/temp_test -?
Usage: bla bla
~ # /tmp/temp_test -y
/tmp/temp_test: invalid option -- 'y'
Usage: bla bla
~ #
More information in man page.

C in Linux - using execle() to output an environment variable?

Program 1
In program 1 I have attempted to create the sole environment variable envar putting it in the env array which is passed to the execle function for the environments creation which program 2 will be run in.
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]){
int ret;
char envar[] = "Big ol' environment variable ;D";
char *env[2] = {envar, 0};
ret = execle("./exec_test1.1", "exec_test1.1", 0, env);
printf("my prog failed ret = %d", ret);
return 0;
}
Program 2
I intended this code in the same directory to retrieve the environment variable envar on execution and to print it. However I the output in its place is null "memes and dis (null)" I have searched but can't see my mistake. Program two is almost identical to another I found for the same purpose so I assume my mistake is in program one.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
char *envptr = getenv("envar");
printf("memes and dis %s\n", envptr);
return 0;
}
Thanks
You have wrong envar variable format - it must be NAME=VALUE. So fixing program 1 to:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int ret;
char envar[] = "envar=Big ol' environment variable ;D";
char *env[2] = {envar, 0};
ret = execle("./exec_test1.1", "exec_test1.1", 0, env);
printf("my prog failed ret = %d", ret);
return 0;
}
should make it work.
(I also took some liberty and formatted the code to make it more readable)

Basic C programming question

I've just started to learn C and it's going pretty slow...I wanted to write a program that takes in an integer argument and returns it's doubled value (aka take in integer, multiply by 2, and printf that value).
I purposely did not want to use the scanf function. Here's what I have so far and what is not compiling...
#include <stdio.h>
int main(int index)
{
if (!(index)) {
printf("No index given");
return 1;
}
a = index*2;
printf("Mult by 2 %d",a);
return 0;
}
So basically when the program is executed I want to supply the index integer. So, in cygwin, I would write something like ./a 10 and 10 would be stored into the index variable.
Also, I want to program to return "No index given" and exit if no index value was supplied...
Anyone care to help what I'm doing wrong?
EDIT:
This code returns 1 error upon compilation and is based on the help by #James:
#include <stdio.h>
int main(int 1, char index)
{
int index, a;
if (!(index)) {
printf("No index given");
return 1;
}
a = index*2;
printf("Mult by 2 %d",a);
return 0;
}
EDIT 2: Consider a simpler program where a value is just taken and echoed back (as shown below)
#include <stdio.h>
int main(int argc, char* argv[])
{
int index;
index = argv[1];
printf("Index is %d, ", index);
/*if (!(index)) {
printf("No index given");
return 1;
}
a = index*2;
printf("Mult by 2 %d",a);*/
return 0;
}
This program fails to compile...Any ideas?!? Ugh.
EDIT 3: This is the code that finally compiled and works. Thanks all!
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
if (argc <= 1)
{
printf("No index given");
return 1;
}
int i;
i = atoi(argv[1]); // convert string in argv[1] to integer
int a;
a = i*2;
printf("Mult by 2: %d",a);
return 0;
}
Thanks!
Amit
There are only two guaranteed-to-work prototypes for the main function: one takes no arguments (int main(void)), the other takes two arguments and looks like this:
int main(int argc, char* argv[])
argc is the number of arguments passed to the program, and argv is an array containing the arguments passed to the program.
If you want to pass an argument when you run the program (and not prompt the user for input), you will need to
use the form of main taking arguments,
check to make sure argc is greater than one (argv[0] is the program name, or should be),
convert argv[1] from its string representation to an integer, using strtol, sscanf, or some other library function (avoid atoi: it provides no usable error reporting),
then use that integer.
As you probably know, main() is a "special" function, which expects either 0 or two arguments: int argc, and char **argv, where argc is automagically assigned the number of arguments in the argument array argv. So, whatever arguments you pass to main() will be stored in argv, and that is from where you need to access your arguments.
This link should help.
The arguments you are passing into the program are text, and so main will receive them as strings. It splits the command line arguments by whitespace and passes them in as an array of strings, along with a number stating the number of parameters it is giving you. The program will always have at least one argument, the name of the file you ran the program as (which is in this case "a"). This string is always found at argv[0].
As the other answers stated, the correct signature for main is int main(int argc, char* argv[]). When you run ./a 10, argc will be 2 and argv[1] will be the string "10". You will need to convert this string to an integer to multiply it by 2, using something like int i = atoi(argv[1]); or int i; sscanf(argv[1], "%d", &i);.
Here is a correction to your code using the proper prototype for a Main with command line arguments.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
if (argc <= 1)
{
printf("No index given");
return 1;
}
int i = atoi(argv[1]); // convert string in argv[1] to integer
int a = i*2;
printf("Mult by 2 %d",a);
return 0;
}

Resources