How can I read a file with read () and O_DIRECT in C ++ on Linux?

I am looking for a solution to solve the problem described above.

Here is my "code not working". charsInCurrentBuffer always returns -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;
+2
source share
1 answer

When you are readfrom O_DIRECTfd, "alignment of the user buffer and file offset must be a multiple of the size of the logical block of the file system" (quoted from the openman page ) on Linux. Other environments may have different restrictions on this, and in fact it depends on the file system.

This will not be the case with newgeneral (unless you are lucky).

posix_memalign, , (BLOCK_SIZE + BUFSIZE) .

new, - , , , .

., , LKML Notes .

+7

All Articles