我尝试使用 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] = ' ';
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 errorn"); 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));