I want to implement logging functionality in C and log messages to both stdout and some file. I would like to write something like fprintf(logout, "msg"); with somehow declared FILE* logout which will redirect strings to both stdout and some file. Is it possible?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
You apparently want a
FILE
-like object that redirects its writes to two underlyingFILE
s (stdout
and the log file). Standard C doesn't allow "subclassing"FILE
objects in any way, so this is not possible in C. However, GNU libc does, so if your program is Linux-only, you can do that with some programming. As this is extremely non-portable, it is strongly recommended against.A more portable way to achieve this is by writing to a pipe and creating a process or thread that reads from the pipe and writes to both underlying files. For example, assuming POSIX:
Both approach add a good deal of complication to your program which should be justified by a very good reason. What you want is to use a logging framework that allows writing to multiple outputs (they all do), or write your own as outlined by H2CO3's answer.
Why don't you make your very own logging function?
If this is on Linux, you can open a pipe to the
tee
command: