Entering command line arguments

I am not sure how to enter command line arguments when I run the executable of the file below. I want check an make sure that only two arguments get into the main() before running the rest of the code. I'm using bash on linux. Any help would be awesome.

An example that I have tried to test for 2 arguments in command line -
arg1 arg2 > ./a.out
This of course does not work but am I thinking about this all wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int main(int argc, char **argv){
	//check for valid command line arguments
	if(argc != 2){
		printf("usage: ./live_coding_2 file_name\n");
		exit(1);
	}

	//open the file
	FILE *f = fopen(argv[1], "r");
	
	//error check file opened correctly
	if(f == NULL){
		//print useful error message (including errno) and exit gracefully
		perror("file failed to open, ERRNO");
		exit(1);
	}

	//close the file and check for error
	if(fclose(f) == EOF){
		//print useful error message (including errno) and exit gracefully
		perror("file failed to close, ERRNO");
		exit(1);
	}

	//exit
	exit(0);
}
Just to clarify: do you call your program as arg1 arg2 > ./a.out (program name arg1, one argument is arg2 and output is redirected to ./a.out)?

What exactly does not work?
I was thinking that arg1 and arg2 would be the values, not programs, passed to a.out main() and my if(argc !=2) code would determine if user entered two arguments.

I have been looking into how this all works. From what I understand now, I enter the program ./a.out followed my args. If I am checking to see if argc == 2 then I only enter one arg on the command line(./a.out arg) becuase the program itself(./a.out) counts as one arg and thus making argc == 2. Is this correct?

If I am checking to see if argc == 2 then I only enter one arg on the command line(./a.out arg) becuase the program itself(./a.out) counts as one arg and thus making argc == 2. Is this correct?
Yes.
This is correct way to call program with name a.out and give it one argument arg. In this case argc will be equal to 2 and argv[0] will contain "a.out", argv[1] will contain "arg".

Line you posted earlier (arg1 arg2 > ./a.out ) does something completely different.
Got it. Thanks again.
Topic archived. No new replies allowed.