sun4lower
3/16/2018 - 10:35 AM

Redirect in shell

redirect stdout、stdin and stderr.

#include <stdio.h>
int main()
{
  int a;
  int b;
  printf("type the first value...\n");
  scanf("%d", &a);
  printf("type the second value...\n");
  scanf("%d", &b);
  if(0 == b) {
    fprintf(stderr, "the second value can't be zero!\n");
    return 1;
  }
  printf("%d / %d = %d\n", a, b, a/b);
  return 0;
}
# output
# ./main.out [1]>> output.txt     append
# ./main.out [1]> output.txt      overwite
# input
# ./main.out < input.txt
# error
# ./main.out 2> error.txt
gcc redirect.c -o main.out
./main.out >>output.txt
cat output.txt
#type the first value...
#type the second value...
#2 / 1 = 2
./main.out >output.txt
cat input.txt
#2
#0
./main.out >output.txt <input.txt 2>error.txt
cat output.txt
#type the first value...
#type the second value...
cat error.txt
#the second value can't be zero!