fseek在打开文件指针上失败

时间:2014-09-24 16:28:51

标签: c file fseek libmagic

我和fseek有问题。我有一个包含提取的HTTP数据的文件指针。然后我让libmagic确定文件的mime类型,然后想要倒回:

char *mime_type (int fd)
{
    char *mime;
    magic_t magic;

    magic = magic_open(MAGIC_MIME_TYPE);
    magic_load(magic, MAGIC_FILE_NAME);
    mime = (char*)magic_descriptor(magic, fd);

    magic_close(magic);
    return (mime);
}

int fetch_pull() {
    fetch_state = fopen("/tmp/curl_0", "r");
    if (fetch_state == NULL) {
      perror("fetch_pull(): Could not open file handle");
      return (1);
    }
    fd = fileno(fetch_state);
    mime = mime_type(fd);
    if (fseek(fetch_state, 0L, SEEK_SET) != 0) {
      perror("fetch_pull(): Could not rewind file handle");
      return (1);
    }
    if (mime != NULL && strstr(mime, "text/") != NULL) {
      /* do things */
    } else if (mime != NULL && strstr(mime, "image/") != NULL) {
      /* do other things */
    }
    return (0);
}

抛出" fetch_pull():无法倒回文件句柄:错误的文件描述符"。有什么问题?

1 个答案:

答案 0 :(得分:2)

/tmp/curl_0是管道,不是吗?你无法倒回管道。什么读不见了。

你无法组合FILE操作和文件描述符操作,因为FILE有一个额外的缓冲区,它们可以提前读取。

如果/tmp/curl_0regular file,请使用open(const char *path, int oflag, ...)打开文件描述符。在调用mime_type(fd)之后,您可以先回滚流,然后使用fdopen(int fildes, const char *mode)将文件描述符包装到FILE句柄中。或者只是关闭文件描述符并在之后使用常规fopen()

int fd = open("/tmp/curl_0", O_RDONLY);
if (fd == -1) {
    perror("Could not open file");
    return -1;
}
char *mime = mime_type(fd);

    /***** EITHER: */

close(fd);
FILE *file = fopen("/tmp/curl_0", "r");

    /***** OR (the worse option!) */

if (lseek(fd, 0, SEEK_SET) == -1) {
    perror("Could not seek");
    return -1;
}
FILE *fdopen = fopen(fd, "r");

    /***********/

if (!file) {
    perror("Could not open file");
    return -1;
}
/* do things */
fclose(file);