我正在尝试编写一个简单的程序,通过封装函数来读取文件,如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
我希望它从文件本身打印一些值,而不是一些代表我不太理解的数字和斜线。为什么会这样?