reading command line argument - c

can anyone point me to the problem over here? This compiles but it won't print anything. I need to compare the string from command line argument with the string "hello".
Thanks!
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
if (argc == 0)
{
printf("No arguments passed!\n");
}
char *str = argv[1];
if(strcmp("hello", str)==0)
{
printf("Yes, I find it");
}
else
{
printf("nothing");
}
return 0;
}

My ESP suggests that you're running this in an interactive editor/debugger, such as Microsoft Studio. You probably haven't configured the environment to pass any command-line parameters, so you expect to see nothing as your output.
However, you access argv[1], which does not exist, creating a seg-fault, and the program aborts before there is any output.
To fix this, check the value of argc first, and make sure you don't access invalid memory.
Also, I recommend putting a \n at the end of each printf to help flush any buffered output to the console.
int main(int argc, char *argv[])
{
if (argc == 0)
{
printf("No arguments passed!\n");
}
else if(strcmp("hello", argv[1])==0)
{
printf("Yes, I find it\n");
}
else
{
printf("nothing\n");
}
return 0;
}
When you run this, you should see:
$prompt: myprogram
No arguments passed!
$prompt: myprogram hello
Yes, I find it
$prompt: myprogram world
nothing

The problem is the command you're using to run it. As you commented:
i run program > test hello or > test hi and the output is nothing
The > is redirecting output, and ends up giving you no command line arguments. What you want is simply program hello without the output redirection.

#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
if (argc < 2 || 0 != strcmp("hello", argv[1]))
printf("nothing\n");
else
printf("yes, found it\n");
return 0;
}
and output
bash-3.2$ gcc 1.c -o 1
bash-3.2$ ./1 hello1
nothing
bash-3.2$ ./1 hello
yes, found it
bash-3.2$ ./1
nothing

Try calling your program something different to 'test'

Related

Running C program with textfile as a parameter doesn't work

I have a simple program "prog.c" in C:
#include<stdio.h>
int main(int argc, char *argv[]) {
printf("Count: %d\n", argc);
printf("Text: %s\n", argv[1]);
return 0;
}
When I compile the program and run with a .txt file as parameter, the program does not recognize this parameter at all.
I compile with: gcc prog.c
which creates an "a.exe" file.
Then I run the .exe program with .txt file as argument (tried all options below):
a < text.txt
a.exe < text.txt
The output is always
Count: 1
Text: (null)
I am running everything on Win10 and using MinGW for compilation.
You want to check that argv[1] is set before referencing it with:
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Count: %d\n", argc);
if(argc > 1) {
printf("Text: %s\n", argv[1]);
}
}
Then you would run it like this:
./your_program argument
Count: 2
Text: argument
When you use < test.txt the file test.txt is copied to standard input of the program. You would use, for example, read() or fread() to read said input.

Using environmental variable to execute a different file

I am a little bit stuck. I have a C program which includes the environmental variable $USER. The goal is to use the environmental variable to execute a different file using command injection.
I already tried different ways of declaring USER.
e.g.: Declaring USER as
env USER=">/dev/null ; cat /home/Steve/Public/file2.txt".
Unfortunately, that did not work.
C program:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
// Execute any shell command
void execute(char *cmd)
{
execl("/bin/bash", "bash", "-p", "-c", cmd, NULL);
}
void sanitise(char *password)
{
int i,j;
char tmp[15];
// remove non-alphabet characters from passwords
j=0;
for(i=0; i < 15; ++i)
if(password[i] >= 'a' && password[i] <= 'z') {
tmp[j]=password[i];
++j;
} else break;
tmp[j] = '\0';
strcpy(password, tmp);
}
int authenticate(char *str)
{
char stored_password[15]="";
char pass[15];
char path[128] = "/home/Steve/private/password";
int i;
FILE *fpp;
int auth=0;
fpp = fopen(path, "r");
if(fpp == NULL)
{
printf("Password file %s not found\n", path);
exit(1);
}
fgets(stored_password, 15, fpp);
sanitise(stored_password);
strcpy(pass, str);
sanitise(pass);
if(strcmp(stored_password,pass) == 0)
auth=1;
else {
auth=0;
}
fclose(fpp);
return auth;
}
int main(int argc, char* argv[], char *envp[])
{
char error[256] = "/home/Steve/Public/errormessage.sh $USER ";
char pass[15];
if(argc < 2)
{
printf("Usage: %s password\n", argv[0]);
return 0;
}
// copy only 15 characters from user input, to prevent stack smashing
strncpy(pass, argv[1], 15);
pass[14]='\0';
if(!authenticate(pass)) {
// Log all failed attempts
printf("Wrong password. This incident has been logged.\n");
strcat(error, pass);
execute(error); // Execute script to log events
return 0;
}
// Display 'secret-file2'
execute("cat /home/Steve/Public/file2.txt");
return 0;
}
The goal would be to make the program output the file from the variable USER and not the initial file path declared in the error char. Ideally, without changing the C program at all.
Can anyone please tell me what I am missing here?
If you wish to use your C program with a fresh seted ${USER} variable "env -i" is what you should use.
Example: env -i USER='injected code' name_of_c_program
If that's what the program is doing, it will execute the following command:
/home/Steve/Public/errormessage.sh $USER <provided-password>
Since you control the provided password (that is, you can pass what you want in argv[1] as long as it's max 14 characters), you can just execute another bash shell as well, and then use it to run any command you want. There really is no need to tamper with $USER.
$ ./program '; bash'
Wrong password. This incident has been logged.
$ <--- another bash shell has now started
$ cat /home/Steve/Public/file2.txt
...contents of file2.txt...
If you want to run it with a single command, this should work:
echo 'cat /home/Steve/Public/file2.txt' | ./program '; bash'
Use 'getenv' library function to get the value of environment variable(USER). And then run the command using 'system(path)'.
#include <stdlib.h>
...
char path[256] = "/home/Steve/Public/file1.sh ";
strcat( path, getenv("USER") );
//char path[256];
//sprintf(file,"%s%s","/home/Steve/Public/file1.sh ",getenv("USER"));
...

How to run a parameter while executing a C file?

I have a working program that computes the cube of a number in a compute_cube.c file. It compiles into compute_cube.
Now I would like to run it through the terminal like this:
./compute_cube 3
And then the terminal would show my program's result (27).
How would I go about doing this? What should I be reading up on?
Use C language's argc and argv:
int main(int argc, char **argv)
{
if (argc > 1)
printf("%s", argv[1]);
}
I know its already been answered but... argc of course = 0-based number of command line args including program name at index 0 and argv contains actual command line text.
#include <stdio.h>
int main(int argc, char **argv) {
if (argc > 1) {
int n = atoi(argv[1]);
printf ("%d^3 = %d\n", n, n*n*n);
return 0;
}
else printf("Usage: %s <num>\n", argv[0]);
return 1;
}

Print in text instead of binary format in cat implementation

The implementation of the cat program is printing in binary format on the Ubuntu terminal. I am using the stdout macro (object of type FILE*).
#include <stdio.h>
main(int argc, char** argv)
{
FILE *fp;
void add(FILE*, FILE*);
if (argc==1)
add(stdin,stdout);
else
while(--argc>0)
{
if ((fp=fopen(*++argv,"r"))==NULL)
{
printf("cat:can't open %s\n",*argv);
return 1;
}
else
{
add(fp,stdout); // printing all the file content on the screen.
fclose(fp);
}
return(0);
}
}
void add(FILE*p,FILE*q)
{
int c;
while((c=fgetc(p))!=EOF)
{
fputc(c,q);
}
}
Now, how can I print in text format instead of binary format?
The error is in how you loop over the arguments. Stripping your code of the actual file processing and replacing it with a print statement (and also nicely indenting it), we get:
if (argc == 1)
printf("stdin\n");
else
while (--argv > 0) {
printf("'%s'\n", *++argv);
}
You have mistyped argc for argv in your code. That means you decrement the pointer to the first argument and then increment it again before processing the file. Effectively, you end up processing argv[0] over and over. That file is the program itself, which is binary and contains many non-printable characters.
You should chzange the loop to
while (--argc > 0) {
printf("'%s'\n", *++argv);
}
or use a pedestrian for loop:
for (int i = 1; i < argc; i++) {
printf("'%s'\n", argv[i]);
}
program has no any error only typo mistake argv instead argc rest all is good even than above suggested answer

How to execute a c file on the command line

I am very new to C programming, and have written this C program that takes in an input N, and gives a list of all the numbers up to N that are exactly divisible by 7. The program I have written is as follows;
# include <stdio.h>
int main(){
int c,n,k;
int i=0;
int AnswerList [1000];
printf("Enter the number\n");
scanf("%d", &n);
for (c=1;c<=n;c++){
if(c%7==0){
AnswerList[i]=c;
i++;
}
}
for (k=0;k<=i;k++){
printf("%d\n", AnswerList[k]);
}
return 0;
}
I need my program to run such that if N equals 27, I should be able to type into the command line
./byseven 27
In other words, I need to write code that bypasses the printf line I think. I would appreciate any help.
Thanks a lot.
Use command-line arguments. A simple example:
int main(int argc, char **argv) {
if (argc < 2) {
printf("Usage: %s N\n", argv[0]);
return 0;
}
int N = atoi(argv[1]); // atoi is used to convert a string to an int
// your code
}
You should use int main(int argc, char** argv) definition. Then argc will be number of your params (first param is always the name of your program), and argv is array of string which contains that params. And scanf function is not needed therefore.
gcc -o hello hello.c
It will compile and produced an exectuable file called hello. To run program type:
./hello

Resources