2010-09-16 42 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!)。