简体   繁体   中英

Piping output of C program to file (bash)

I'm just trying my hand in bash, so I wrote a simple program in C to count the number of characters in a file.

This is my C program:

#include <stdio.h>

int main()
{
  int i, nc;
  nc = 0;
  i = getchar();
  while (i!=EOF){
    nc = nc + 1;
    i = getchar();
  }
  printf("%d\n",nc);

  return 0;
}

This is the bash command I'm using to compile and execute:

gcc sign.c < bright_side_of_life > output

My output file is completely empty though. Where am I going wrong?

You have to compile first, then run:

gcc -o sign sign.c
./sign < bright_side_of_life > output

Also, technically this is not piping the output of the program to a file; it is simply redirecting it. If you really wanted a pipe involved, you'd probably go in for some 'feline abuse' (meaning, use the 'cat' command):

./sign < bright_side_of_life | cat > output

However, the I/O redirection is more normal and (though it really doesn't matter in this context) more efficient.

gcc sign.c -o output
./output < bright_side_of_life > size.txt

and i hope you are actually practising your C language. otherwise, just use the wc tool

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM