从文件描述符更改为FILE结构,反之亦然,可以使用以下方法:
#include<stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd = open("test.txt", O_RDONLY);
if (fd == -1) {
perror("open");
return 1;
}
FILE *fp = fdopen(fd, "r");
if (fp == NULL) {
perror("fdopen");
close(fd);
return 1;
}
// 使用fp进行文件操作
fclose(fp);
return 0;
}
#include<stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main() {
FILE *fp = fopen("test.txt", "r");
if (fp == NULL) {
perror("fopen");
return 1;
}
int fd = fileno(fp);
if (fd == -1) {
perror("fileno");
fclose(fp);
return 1;
}
// 使用fd进行文件操作
close(fd);
fclose(fp);
return 0;
}
注意:在使用文件描述符和FILE结构时,需要注意读写的同步,避免出现数据不一致的情况。同时,在使用文件描述符时,需要注意关闭文件描述符,以避免资源泄漏。
领取专属 10元无门槛券
手把手带您无忧上云