来自 fread 的错误文件描述符

bad file descriptor from fread

我尝试使用 read() 从文件中获取一些字符只是为了学习这个 API。我在同一目录中创建了一个名为 "file" 的文件,它包含 1000 个字符。但是我收到一条错误消息:

read: %m: Bad file descriptor

代码如下:

#include <stdio.h>
#include <error.h>

int read_indent(int sockfd){
  int sport, cport;
  char user[2], rtype[2], addinfo[2];
  char buffer[17];

  if(read(sockfd, buffer, sizeof(buffer)) <= 0) {
    perror("read: %m");
    return -1;
  }

  buffer[sizeof(buffer)-1] = '[=11=]';

  sscanf(buffer, "%d:%d:%s:%s:%s", &sport, &cport, rtype, user, addinfo);
  printf("%d:%d:%s:%s:%s", sport, cport, rtype, user, addinfo);
  return 0;
}

int main(){
  FILE *file_pt = fopen("file", "r");
  if(file_pt == NULL) { printf("fopen error\n"); return -1;}
  char buf[128];
  int a = read_indent(file_pt);
  fclose(file_pt);
  return 0;
}

更新 1:编译消息

test.c: In function ‘main’:
test.c:27:2: warning: passing argument 1 of ‘read_indent’ makes integer from pointer without a cast [enabled by default]
  int a = read_indent(file_pt);
  ^
test.c:4:5: note: expected ‘int’ but argument is of type ‘struct FILE *’
 int read_indent(int sockfd){

您的 read_indent 函数接受文件描述符,但您传递的是 FILE* 指针。尝试使用 fileno:

FILE* 指针转换为文件描述符
int a = read_indent(fileno(file_pt));