如何在Linux上使用C ++中的read()和O_DIRECT读取文件? [英] How can I read a file with read() and O_DIRECT in C++ on Linux?

查看:836
本文介绍了如何在Linux上使用C ++中的read()和O_DIRECT读取文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个解决方案来解决上述问题。



这里是我的不工作的代码。 charsInCurrentBuffer总是返回-1!

  #define BUFSIZE 512 

char * bufferA = new char [BUFSIZE];
char * bufferB = new char [BUFSIZE];

const char * inputFile =in.txt;

if((fdInputFile = open(inputFile,O_DIRECT))!= -1){
cout< 输入开! << endl;
} else {
cout<< 无法打开输入文件!
}

int charsInCurrentBuffer = read(fdInputFile,currBuffer,BUFSIZE);
cout<< charsInCurrentBuffer< endl;

解决方案

code>从 O_DIRECT fd,用户缓冲区和文件偏移量的对齐必须都是文件系统的逻辑块大小的倍数(引用从 open code>手册页)。



new 不会出现这种情况$ c>通常(除非你幸运)。



如果你的平台有一个 posix_memalign 或者只是分配一个更大的缓冲区(BLOCK_SIZE + BUFSIZE)并使用它的块大小对齐的部分。



如果你想坚持使用 new ,您将需要使用某种形式的展示位置新功能与上述功能相结合,但是我不太熟悉这一点,以展示该功能如何工作。



如需参考,请参阅 LKML上的线程,或上面引用的手册页的Notes部分。


I'm searching for a solution to solve the above described problem.

Here's my "doesn't working code". charsInCurrentBuffer returns always -1!

#define BUFSIZE 512

char *bufferA = new char[BUFSIZE];
char *bufferB = new char[BUFSIZE];

const char *inputFile = "in.txt";

if ( (fdInputFile = open(inputFile, O_DIRECT) ) != -1) {
    cout << "input opened!" << endl;
} else {
    cout << "can't open input file!";
}

int charsInCurrentBuffer = read(fdInputFile, currBuffer, BUFSIZE);
cout << charsInCurrentBuffer << endl;

解决方案

When you read from an O_DIRECT fd, the "alignment of the user buffer and the file offset must all be multiples of the logical block size of the file system" (quoted from the open man page) on Linux. Other environments might have different constraints on this, and it's in fact filesystem dependent.

That's not going to be the case with new generally (unless you get lucky).

You should consider using a posix_memalign function if your platform has that, or simply allocate a larger buffer (BLOCK_SIZE + BUFSIZE) and use the block-size aligned part of it.

If you want to stick with new, you're going to need to use some form of placement new combined with the above, but I'm not familiar enough with that to show how that would work.

For reference, see for example this thread on LKML, or the Notes section of the above-quoted man page.

这篇关于如何在Linux上使用C ++中的read()和O_DIRECT读取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆