乐闻世界logo
搜索文章和话题

How to get a FILE pointer from a file descriptor?

1个答案

1

In C programming, if you have a file descriptor and wish to convert it to a FILE pointer, you can use the fdopen function. This function associates an existing file descriptor with a new standard I/O stream.

Syntax

c
FILE *fdopen(int fd, const char *mode);
  • fd: This is the already opened file descriptor.
  • mode: This specifies the type of operation you intend to perform on the file, such as reading or writing, which matches the mode string used in the fopen function.

Return Value

If successful, the fdopen function returns a new file stream; if it fails, it returns NULL.

Example Code

Assume you have already opened a file using the open function and obtained a file descriptor; now you want to obtain the corresponding FILE pointer for standard I/O operations.

c
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> int main() { int fd = open("example.txt", O_RDONLY); if (fd == -1) { perror("Unable to open file"); return EXIT_FAILURE; } FILE *file = fdopen(fd, "r"); if (file == NULL) { perror("Failed to convert file descriptor to FILE pointer"); close(fd); return EXIT_FAILURE; } // Now you can use standard I/O functions such as fscanf, fprintf, etc. to process the file char buffer[1024]; if (fgets(buffer, sizeof(buffer), file) != NULL) { printf("First line: %s", buffer); } else { perror("Failed to read from file"); } // Closing the FILE pointer also closes the file descriptor fclose(file); return EXIT_SUCCESS; }

In this example, we first open a file using the open function and obtain the file descriptor fd. Then, we convert this file descriptor to a FILE pointer using the fdopen function. Once the FILE pointer is obtained, standard I/O library functions can be used for file operations.

This method is particularly useful when integrating low-level operations (such as read and write functions) with high-level operations (such as fprintf and fscanf).

2024年6月29日 12:07 回复

你的答案