0
我想寫一個簡單的程序,通過封裝函數如open
,lseek
,pread
讀取文件。嘗試從文件讀取使用文件描述符打印數字和斜線到控制檯
我的測試文件中包含:
first second third forth fifth sixth
seventh eighth
我試圖主函數讀取20個字節,從文件偏移10:
#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
我期望它從文件本身打印一些值,而不是一些數字和斜槓代表我不瞭解的東西。 這是爲什麼發生?
我實現了你在3中寫的(從buf調用讀取中刪除&),它工作。我採取的其他點作爲額外的有用的提示。謝謝!! – Eyzuky
緩衝區需要在堆棧或堆上存在。 'pread'函數將不會爲你分配它。如果您忽略寫入堆棧或堆損壞後不想寫入的位置。 –
我將按照你的說明實現初始化,謝謝先生。 – Eyzuky