Better not to do that. It is necessary to redirect STDOUT to a file, run the program as
program_name > hello_world.txt
But if you really need, for example for a demon, then:
- open the file with
::open() - do not use ::fopen() , as there will be a headache with buffers and their matching. - duplicate descriptors with
dup2() - ...
- PROFIT!
more precisely, you simply continue to use std::cout as before, but the text will fall into the file. Already need to close the file descriptor itself.
Here is an example:
#include <fcntl.h> #include <unistd.h> #include <cstdlib> #include <cstdint> #include <iostream> using namespace std; int main() { auto fd = ::open("./hello.txt", O_APPEND | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH); // Дуплицируем наш дескриптор на стандартный выход dup2(fd, STDOUT_FILENO); // С этого момента, всё, что попадает в std::cout - попадает в файл. cout << "Hello, world!\n"; cout << flush; ::close(fd); return 0; }
Similarly, you can do for STDERR_FILENO - the standard error stream. It is used by std::cerr and std::clog (the first is not buffered, the second, like std::cout is buffered).
For Windows, it is worthwhile to clarify the behavior and where are the ::open() and dup2() declarations and their alternatives: