(1) 函数 fdopen():
++ 例子:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd = open("example.txt", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
if (fd == -1) {
perror("open");
return 1;
}
FILE *file = fdopen(fd, "w");
if (file == NULL) {
perror("fdopen");
close(fd); // 别忘了在失败时关闭文件描述符
return 1;
}
fprintf(file, "Hello, fdopen!\n");
fclose(file); // 使用 fclose 关闭文件,它也会关闭底层的文件描述符
// 注意:不需要再次调用 close(fd),因为 fclose 已经做了这件事。
return 0;
}
(2) fielno() 函数:
++ 例子:
#include <stdio.h>
#include <unistd.h> // 用于 close 函数
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
perror("Failed to open file");
return 1;
}
int fd = fileno(file);
printf("File descriptor: %d\n", fd);
// 在这里可以使用文件描述符 `fd` 进行其他操作,比如读取或写入
// 关闭文件(注意:这里只是关闭了 FILE* 对应的文件流,文件描述符可能仍然有效)
fclose(file);
// 如果需要,也可以显式关闭文件描述符(但通常不需要,因为 fclose 会处理)
// close(fd); // 小心使用,可能导致未定义行为,因为 fclose 可能已经关闭了它
return 0;
}
(3)
谢谢