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 :
$ TESTit should display0( we used the default values).$ TEST < argsTest.jsondisplay5.$ TEST 4 3display7.
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.
TEST, stdin is not empty. Instead, stdin is whatever you enter on the terminal. You will have to press Ctrl+D for the terminal input to be considered empty. I would strongly encourage you to rethink your interface and work with the system instead of against it. Canonical behavior is easier to implement and easier to use.EOFfrom the buffer so he had to send it with` Ctrl+d` , in my case i want to do it automatically without getting in the if statement . Even if i have to change the if statement.