c - fseek 在打开的文件指针上失败

标签 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():无法倒回文件句柄:错误的文件描述符”。怎么了?

最佳答案

/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);

关于c - fseek 在打开的文件指针上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26021990/

相关文章:

c - 如何在文件上使用 SEEK_CUR*

c - 换行符在 fgets() 之后保留在缓冲区中?

c - 使用 GCC 链接对象的两种方法?

c++ - 将文件读入数组

c# - 为什么在尝试读取正在写入的文件时出现未处理的异常 : System. IO.IOException?

c - 在c中使用fseek和结构数组

c - C 中的 fseek() API 和错误代码

c++ - C/C++ 优化器能否决定延迟评估仅用于短路评估的值?

C 问题中将 Double 转换为 Int

php - 如何读取文件,如果文件或目录在 Windows 共享驱动器(映射驱动器)上可用,请使用 php