[英]Trying to read from a file using file descriptor prints numbers and slashes to console
我正在尝试编写一个简单的程序,通过封装诸如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
我希望它能从文件本身中打印出一些值,而不是一些数字和斜杠来代表我不太了解的东西。 为什么会这样?
以下更改将使您的程序正常工作:
您的缓冲区必须是一个存在的char数组,并且不使用地址运算符&
情况下调用CacheFS_pread
函数。 还使用buffer size minus 1
因为pread
函数将覆盖终止\\0
因为它仅读取文件的n个字节。 我在这里使用零初始化的char数组,以便至少在结尾处有一个以\\0
结尾的空值。
char buf[20] = { '\\0' }; // declare and initialize with zeros CacheFS_pread(fd1, buf, sizeof(buf) - 1, 10);
出于类型安全原因,您的函数标头应仅接受char指针。
int CacheFS_pread(int file_id, char* buf, size_t count, off_t offset)
这样,您的前置呼叫将没有地址运算符&
:
pread(file_id, buf, count, seek);
输出: nd third forth fift
因为缓冲区只有20!
我还要检查您的计算和if语句是否正确。 我感觉这并不完全正确。 我也建议使用pread的返回值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.