Problem:
Constructing an fstream object directly from a POSIX file descriptor can be challenging in C .
Solution:
Libstd
For libstdc , there is no standard way to do this. However, libstdc offers a non-standard constructor for fstream that takes a file descriptor input.
Example:
#include <ext/stdio_filebuf.h> using namespace std; int main() { int posix_handle = open("file.txt", O_RDONLY); // Open a file with POSIX handle __gnu_cxx::stdio_filebuf<char> filebuf(posix_handle, ios::in); // Create stdio_filebuf from POSIX handle ifstream ifs(&filebuf); // Create ifstream from stdio_filebuf // Read from the file }
Microsoft Visual C
Microsoft Visual C also provides a non-standard constructor for ifstream that accepts a FILE pointer. You can call _fdopen to obtain the FILE from the POSIX file descriptor.
Example:
#include <cstdio> #include <fstream> using namespace std; FILE *_file = fopen("file.txt", "r"); // Open a file with C file handle ifstream ifs(_fdopen(_fileno(_file), "r")); // Create ifstream from FILE* // Read from the file
Note:
These non-standard constructors may not be available in all C implementations. It is recommended to check the documentation for your specific implementation.
The above is the detailed content of How Can I Construct a C fstream from a POSIX File Descriptor?. For more information, please follow other related articles on the PHP Chinese website!