gpt4 book ai didi

c - 使用 open 和 fdopen 打开文件后程序挂起

转载 作者:太空狗 更新时间:2023-10-29 15:10:55 25 4
gpt4 key购买 nike

<分区>

我将 open()O_RDWR 一起使用,然后将 fdopen() 中的描述符与 "r+"< 一起使用。我首先使用 access() 检查文件是否存在,然后检查 open() 返回 -1,然后检查 FILE *fp 设置来自 fdopen() 不是 NULL

现在,每当我将任何函数(例如 fgets()fgetc())与 fp 一起使用时,程序就会卡在我的终端中。我没有收到编译器警告。有什么想法吗?

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char **argv) {
char buffer[512];
int file_descriptor;
FILE *file;

if (argc != 2) {
puts("ERROR: Missing argument");
exit(0);
}
else if (access(argv[1], F_OK) == -1) { // Check if file exists
puts("ERROR: File does not exist");
exit(0);
} else if (file_descriptor = open(argv[1], O_RDWR) == -1) { // Check for open() failure
puts("ERROR: Unable to open file using open()");
exit(0);
}

file = fdopen(file_descriptor, "r+"); // Use descriptor

if (file == NULL) {
puts("ERROR: Unable to open file using fdopen()");
fclose(file);
exit(0);
}

// fscanf(file, "%c", stdout); // Hangs
// fgets(buffer, sizeof(buffer), file); // Hangs
printf("%c", fgetc(file)); // Hangs

fclose(file);

return 0;
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com