【发布时间】:2010-09-16 14:22:51
【问题描述】:
我刚刚学习 D。看起来是一门很棒的语言,但我找不到任何有关文件 I/O 功能的信息。我可能很昏暗(我很擅长!),所以有人能指出我正确的方向吗? 谢谢
【问题讨论】:
-
@Kenny:“刚刚学习”意味着我目前“推荐用于新项目”的版本,即 2。
我刚刚学习 D。看起来是一门很棒的语言,但我找不到任何有关文件 I/O 功能的信息。我可能很昏暗(我很擅长!),所以有人能指出我正确的方向吗? 谢谢
【问题讨论】:
基本上,您使用来自std.stdio 的the 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();
}
【讨论】:
std.stdio 模块呢?
【讨论】:
对于与文件相关的内容(文件属性、一次性读取/写入文件),请查看std.file。对于泛化到标准流(stdin、stdout、stderr)的东西,请查看std.stdio。您可以将std.stdio.File 用于物理磁盘文件和标准流。不要使用std.stream,因为它计划弃用并且不适用于范围(D 相当于迭代器)。
【讨论】:
我个人觉得 C 风格的文件 I/O 是有利的。我发现使用 I/O 是最清晰的方法之一,尤其是在使用二进制文件时。即使在 C++ 中我也不使用流,除了增加安全性之外,它只是简单的笨拙(就像我更喜欢 printf 而不是流一样,D 有一个类型安全的 printf 非常棒!)。
【讨论】: