LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Writing files using O_DIRECT in C (https://www.linuxquestions.org/questions/programming-9/writing-files-using-o_direct-in-c-792203/)

anchit87 02-28-2010 04:02 PM

Writing files using O_DIRECT in C
 
Hi,

I am trying to write .pgm images using the O_DIRECT flag in open().
I have a char* buffer which has the image data.

I know that I have to align the buffers and have done that using posix_memalign() yet only a part of the image gets written.

Has someone used O_DIRECT for writing files successfully? Can you help me on how to proceed with this?

Thanks

neonsignal 02-28-2010 08:51 PM

Quote:

Has someone used O_DIRECT for writing files successfully?
I haven't, because there isn't a good reason to.

However, the following code illustrates its use. Note that both the buffer start and end should be block aligned.
Code:

#define _GNU_SOURCE
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#define BLOCKSIZE 512
char image[] =
{
        'P', '5', ' ', '2', '4', ' ', '7', ' ', '1', '5', '\n',
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 3, 3, 3, 3, 0, 0, 7, 7, 7, 7, 0, 0,11,11,11,11, 0, 0,15,15,15,15, 0,
        0, 3, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0,11, 0, 0, 0, 0, 0,15, 0, 0,15, 0,
        0, 3, 3, 3, 0, 0, 0, 7, 7, 7, 0, 0, 0,11,11,11, 0, 0, 0,15,15,15,15, 0,
        0, 3, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0,11, 0, 0, 0, 0, 0,15, 0, 0, 0, 0,
        0, 3, 0, 0, 0, 0, 0, 7, 7, 7, 7, 0, 0,11,11,11,11, 0, 0,15, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0,
};
int main()
{
        void *buffer;
        posix_memalign(&buffer, BLOCKSIZE, BLOCKSIZE);
        memcpy(buffer, image, sizeof(image));
        int f = open("feep.pgm", O_CREAT|O_TRUNC|O_WRONLY|O_DIRECT, S_IRWXU);
        write(f, buffer, BLOCKSIZE);
        close(f);
        free(buffer);
        return 0;
}



All times are GMT -5. The time now is 08:47 PM.