来自fread的错误文件描述符

时间:2015-03-14 15:56:45

标签: c file io file-descriptor file-pointer

我尝试使用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] = '\0';

  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){

1 个答案:

答案 0 :(得分:2)

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

int a = read_indent(fileno(file_pt));