2010-09-16 20 views
7

我只是學習D.看起來像一個偉大的語言,但我找不到有關文件I/O函數的任何信息。我可能會變得模糊(我擅長這一點!),所以有人可以指點我正確的方向嗎? 謝謝D文件I/O函數

+1

@Kenny:「Just learning」意味着目前爲我推薦的新版本的版本,即2。 – Joey 2010-09-16 14:30:50

回答

10

基本上,您使用std.stdiothe File structure

import std.stdio; 

void writeTest() { 
    auto f = File("1.txt", "w");  // create a file for writing, 
    scope(exit) f.close();    // and close the file when we're done. 
             // (optional) 
    f.writeln("foo");     // write 2 lines of text to it. 
    f.writeln("bar"); 
} 

void readTest() { 
    auto f = File("1.txt");    // open file for reading, 
    scope(exit) f.close();    // and close the file when we're done. 
             // (optional) 
    foreach (str; f.byLine)    // read every line in the file, 
     writeln(":: ", str);    // and print it out. 
} 

void main() { 
    writeTest(); 
    readTest(); 
} 
3

對於專門文件相關的東西(文件屬性,讀/寫一氣呵成的文件),看在std.file。對於推廣到標準流(stdin,stdout,stderr)的東西,請查看std.stdio。對於物理磁盤文件和標準流,您可以使用std.stdio.File。請勿使用std.stream,因爲這是計劃棄用的,並且不適用於範圍(D等效於迭代器)。

0

我個人認爲C風格的文件I/O有利。我發現使用I/O是最明顯的一種,尤其是在使用二進制文件的情況下。即使在C++中,我也不使用流,除了增加安全性之外,它只是簡單的笨拙(很像我喜歡printf over stream,很好的D如何使用類型安全的printf!)。