2011-04-29 92 views
1

有沒有辦法直接寫入磁盤沒有緩存在c + +? 目前我使用:C++中的直接文件訪問?

int open(fileout, O_CREATE | O_WRONLY | O_DIRECT); 
FILE *fh = fdopen(fileout_dev, "wb"); 

是否允許這樣做,有跨平臺的庫?

謝謝阿爾曼。

+4

你是問有關操作系統或在C/C++ RTL擊敗cacheing? – 2011-04-29 10:54:00

+1

或者在硬盤控制器中? – 2011-04-29 11:06:16

+0

我想寫入沒有緩存的文件... – Arman 2011-04-29 11:08:39

回答

1

如果你談論的緩衝,那麼你可以使用setbufsetvbuf

/* setbuf example */ 
#include <stdio.h> 

int main() 
{ 
    char buffer[BUFSIZ]; 
    FILE *pFile1, *pFile2; 

    pFile1=fopen ("myfile.txt","w"); 
    pFile2=fopen ("myfile2.txt","a"); 

    setbuf (pFile1 , buffer); 
    fputs ("This is sent to a buffered stream",pFile1); 
    fflush (pFile1); 

    setbuf (pFile2 , NULL); 
    fputs ("This is sent to an unbuffered stream",pFile2); 

    fclose (pFile1); 
    fclose (pFile2); 

    return 0; 
} 


/* setvbuf example */ 
#include <stdio.h> 

int main() 
{ 
    FILE *pFile; 

    pFile=fopen ("myfile.txt","w"); 

    // _IONBF disables buffering 
    setvbuf (pFile , NULL , _IONBF, 0); 

    // File operations here 

    fclose (pFile); 

    return 0; 
} 
+0

謝謝,跟O_DIRECT一樣嗎? – Arman 2011-04-29 11:04:36

+0

@Arman:「和O_DIRECT一樣嗎?」 No. – 2011-04-29 12:05:53

+0

@Arman:BTW O_DIRECT並不保證你沒有緩存。它只是要求類Unix的內核不要通過這個FD緩存IO。硬件本身可能在內部緩存。 – 2011-04-29 12:09:08