我正在尝试编写一个简单的程序,通过封装open
、lseek
、pread
等函数来读取文件。
我的测试文件包含:
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
我希望它打印文件本身的一些值,而不是一些代表我不太理解的东西的数字和斜杠。 为什么会这样?
最佳答案
以下更改将使您的程序正常工作:
您的缓冲区必须是一个存在的字符数组,然后您的
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);
出于类型安全原因,您的函数头应该只接受字符指针。
int CacheFS_pread(int file_id, char* buf, size_t count, off_t offset)
然后您的 pread 调用没有地址运算符
&
:pread(file_id, buf, count, seek);
输出:nd third fourth fift
因为缓冲区只有 20!
我还会检查您的计算和 if 语句是否正确。我觉得这不完全正确。我还建议使用 pread 的返回值.
关于c++ - 尝试使用文件描述符从文件中读取会打印数字和斜线到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44282870/