I'm learning C language, I'm having trouble with my program.
So, I have this program called TEST
this program should allow me to read the argument either with argv[]
or by using the input stream $ TEST < argsTest.json
.
argsTest.json :
{
"a" = 2,
"b" = 3
}
to simplify my question I will use this simple program :
Struct {
int a;
int b;
} number;
int main(int argc, char **argv) {
json_t * root;
struct number numbers;
int c = 0, i = 0 , result;
char str[1024]; // I'm not using malloc just to simplify my question
// default values
numbers.a = 0;
number.b = 0;
if (argc == 1 && !feof(stdin)) {
while((c = fgetc(stdin)) != EOF) {
str[i]=c;
++i;
}
str[i] = '\0';
.... // code that use jansson library to extract value
/** let's suppose we have extracted the two value int json_a
* and int json_b.
*/
numbers.a = json_a;
numbers.b = json_b;
} else if (argc == 3) {
scanf("%d", numbers.a);
scanf("%d", numbers.b);
}
result = numbers.a + number.b;
printf("%d\n", result);
return 0;
}
So, I'm trying to implement three behaviors :
$ TEST
it should display0
( we used the default values).$ TEST < argsTest.json
display5
.$ TEST 4 3
display7
.
My problem is that if statement if (argc == 1 && !feof(stdin))
, actually
$ TEST
and $ TEST < argsTest.json
have the same statement argc == 1
, so
when run $ TEST
it bug because he enters the first condition.
I want an if statement that will check if the input stream is empty and having 0
argument, so I can implement the first case without getting in the if statement.
Thank you.