Hello all,
I am trying to understand the concept of pipe-ing input/output through a C program. I wrote this simple code:
#include <stdio.h>
#include <stdlib.h>
void in_read (int *foo) {
read (0, foo, 1);
}
void in_write (int foo) {
write (1, &foo, 1);
}
int main (int argc, char **argv) {
int y;
if (argc != 2) {
in_read (&y);
printf ("Y is %d\n", y);
}
else {
y = atoi(argv[1]);
in_write(y);
}
return EXIT_SUCCESS;
}
When I run it with ./a.out 14 | ./a.out
, this produces the expected result of 14.
However, my desire is to take the argv outputs and use it as pipe input to populate data in a struct. Thus, I wrote this more complex code:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int h;
int w;
} box;
void box_read (int *foo) {
read (0, foo, 1);
}
void box_write (int foo) {
write (1, &foo, 1);
}
void box_read_help (box *foo) {
box_read (&foo->h);
box_read (&foo->w);
}
void box_write_help (box *foo) {
box_write (foo->h);
box_write (foo->w);
}
int main (int argc, char **argv) {
box mybox;
if (argc != 3) {
box_read_help (&mybox);
printf ("Height: %d\n", mybox.h);
printf ("Width: %d\n", mybox.w);
}
else {
mybox.h = atoi(argv[1]);
mybox.w = atoi(argv[2]);
box_write_help (&mybox);
}
return EXIT_SUCCESS;
}
And try to run it with ./a.out 16 14 | ./a.out
and do not receive expected output.
The caveat is I can not modify the main()
function or the box_read()
and box_write()
functions-I am only allowed to modify the box_read_help()
and the box_write_help()
I believe my error is in the box_read_help
function, can anyone help me out?
Thanks.