Is it possible to find out how many bytes were printed in the file stream, for example, standard output?

Is it possible for the calling program in C to know how many bytes it printed in the file stream, for example stdout, without actually counting or adding return values printf?

I am trying to implement a control over the amount of output from a C program that uses libraries for printing, but the libraries do not report the amount of data they printed.

I am interested in either a general solution or a Unix-specific one.

+3
source share
4 answers

POSIX-specific: stdout , , st_size ( ls).

. , . POSIX head . , .

+1

, , ftell stdout:

long int start = ftell(stdout);
printf("abcdef\n");
printf("%ld\n", ftell(stdout) - start); // >> 7

Ubuntu Precise: , , , .

$ ./a.out 
abcdef
0
$ ./a.out >tt
$ cat tt
abcdef
7
$ echo `./a.out`
abcdef 0
$ echo `cat tt`
abcdef 7
0

, :

  • , pipe()
  • : stdout ( stdout)
  • : stdout ( stdout) -
  • stdout ( )
  • IPC .

, , .

IPC - , ( / ) , ( , ..) , .

- , .. , , , , , ( , ). , - - , , IPC ; , stdout , eof.

If you need more frequent readings that need to be accurate, then you need something more than copmlex, but this can be achieved by developing a kind of protocol using sockets, pipes or even converters / semaphores / etc in shared memory.

0
source

printf returns the number of bytes written.

Add them.

0
source

All Articles