c++ - 尝试使用文件描述符从文件中读取会打印数字和斜线到控制台

标签 c++ io lseek

我正在尝试编写一个简单的程序,通过封装openlseekpread 等函数来读取文件。

我的测试文件包含:

first second third forth fifth sixth
seventh eighth

我的主函数试图从文件中读取偏移量为 10 的 20 个字节:

#include <iostream>
#include "CacheFS.h"
using namespace std;
int main(int argc, const char * argv[]) {
    char * filename1 = "/Users/Desktop/File";
    int fd1 = CacheFS_open(filename1);
    //read from file and print it
    void* buf[20];
    CacheFS_pread(fd1, &buf, 20, 10);
    cout << (char*)buf << endl;
}

主要功能的实现:

int CacheFS_open(const char *pathname)
{
    mode_t modes = O_SYNC | 0 | O_RDONLY;
    int fd = open(pathname, modes);
    return fd;
}

int CacheFS_pread(int file_id, void *buf, size_t count, off_t offset)
{
    off_t seek = lseek(file_id, offset, SEEK_SET);
    off_t fileLength = lseek(file_id, 0, SEEK_END);
    if (count + seek <= fileLength) //this case we are not getting to the file end when readin this chunk
    {
        pread(file_id, &buf, count, seek);
    } else { //count is too big so we can only read a part of the chunk
        off_t size = fileLength - seek;
        pread(file_id, &buf, size, seek);
    }
    return 0;
}

我的主要功能将此打印到控制台:

\350\366\277_\377

我希望它打印文件本身的一些值,而不是一些代表我不太理解的东西的数字和斜杠。 为什么会这样?

最佳答案

以下更改将使您的程序正常工作:

  1. 您的缓冲区必须是一个存在的字符数组,然后您的 CacheFS_pread 函数在没有地址运算符 & 的情况下被调用。还要使用 buffer size minus 1 因为 pread 函数将覆盖终止 \0 因为它只是读取文件的 n 个字节。我在这里使用了一个零初始化的字符数组,这样至少在末尾会有一个空终止 \0

    char buf[20] = { '\0' }; // declare and initialize with zeros
    CacheFS_pread(fd1, buf, sizeof(buf) - 1, 10);
    
  2. 出于类型安全原因,您的函数头应该只接受字符指针。

    int CacheFS_pread(int file_id, char* buf, size_t count, off_t offset)
    
  3. 然后您的 pread 调用没有地址运算符 &:

    pread(file_id, buf, count, seek);
    

输出:nd third fourth fift 因为缓冲区只有 20!

我还会检查您的计算和 if 语句是否正确。我觉得这不完全正确。我还建议使用 pread 的返回值.

关于c++ - 尝试使用文件描述符从文件中读取会打印数字和斜线到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44282870/

相关文章:

java - 读/写项目文件夹中的文件

c - 调用 lseek() 时,POSIX read() 函数不读取任何字节

c - 为什么 lseek 使用偏移量 `-2` 而不是 `-1` 来反向读取?

C++ std::mem_fn 和 std::bind 反过来

c++ - 我如何比较一个字符按字母顺序排列的顺序是高于还是低于另一个?

c++ - 字符串未使用 <openssl/aes> 正确解密

c - 使用 lseek 在 C 中获取文件的大小?

c++ - 在没有终端或 SSH 访问权限的情况下编译 C++?

python - 模块 VTK 无法在 Windows 上读取 Python3 中的文件

io - 在 Julia 中设置多个 I/O 缓冲区的最佳方法是什么?