问题
THE QUESTION
I mean to write C/C++ code such that I am able to specify to a user of the program how to redirect various message categories (each one being output at a file descriptor number that I should know) to different user-selected files. E.g., 3: messages from mild warnings, 4: messages from numeric routines (and not type 3), etc.
EDIT #1 (Top posting)
I managed to redirect stdout
to my fd
file descriptor number from within C with dup2
(I learned today about it).
In this way, I can write to fd
with all the same goodies that I would do with stdout
.
I simply do
int retval = dup2(fd, STDOUT_FILENO);
Now I have a couple of subsequent questions:
How can I remove the redirection from
stdout
tofd
at a later stage in my code? I have found here that I need to first "clone"stdout
, and use the clone as a backup for later restoring. This looks somewhat cumbersome.What if I want to write alternately to
fd
andstdout
in nearby sentences? Moreover, I would likely want to capture both with something likemycomm > out.txt 3> myout.txt
From my current understanding of the use of
dup2
, I would have to repeatedly apply step 1 above, which seems clumsy.
ORIGINAL ATTEMPT
I would need:
Within the code I can write to predefined file descriptor numbers (say, 3)
const int fd = 3; <something that relates fd with an ofstream or FILE *> fp << <whatever stuff>; // C++ style fprintf(...) /* C style */
If the executable generated is
mycomm
, at the command line I can writemycomm 3> myout.txt
I put together code below. It partially does the job, except for at least one undesirable effect: I have to tell the number of bytes to be written. I want something that is smart enough to guess that, in particular when chaining several outputs, as in
cout << myintvar << mystringvar << ", that's it";
I can always write to an ostringstream
, get the length, and use it as an argument, but there might be something neater already available.
I am thinking about creating a class, whose single member is an int
for the file descriptor, but adding the capability to easily smart-write to it.
Is this a correct approach? Is there an alternative, easier, more fool-proof way of achieving this?
Besides, What is a safe way to first check if the "hardcoded" fd
number is available?
My code:
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
using namespace std;
int main() {
const int fd = 3;
char c[100] = "Testing";
ssize_t nbytes = write(fd, (void *) c, strlen(c));
cout << "Wrote " << nbytes << " bytes to file descriptor " << fd << endl;
return 0;
}
来源:https://stackoverflow.com/questions/61852010/smart-write-to-arbitrary-file-descriptor-from-c-c