tags:

views:

120

answers:

4

I'm just learning D. Looks like a great language, but I can't find any info about the file I/O functions. I may be being dim (I'm good at that!), so could somebody point me in the right direction, please? Thanks

+3  A: 

What about the std.stdio module?

Joey
+4  A: 

Basically, you use the File structure from std.stdio.

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();
}
KennyTM
+3  A: 

For stuff related specifically to files (file attributes, reading/writing a file in one go), look in std.file. For stuff that generalizes to standard streams (stdin, stdout, stderr) look in std.stdio. You can use std.stdio.File for both physical disk files and standard streams. Don't use std.stream, as this is scheduled for deprecation and doesn't work with ranges (D's equivalent to iterators).

dsimcha
A: 

Personally I find C-style file I/O favourable. I find it one of the most clear to use I/O's, especially if you work with binary files. Even in C++ I don't use streams, beside added safety it's just plain clumsy (much as I prefer printf over streams, excellent how D has a type-safe printf!).

Daevius