write to file ... trivial?
Jesse Phillips
jessekphillips+D at gmail.com
Wed Oct 6 18:09:54 PDT 2010
Dr. Smith Wrote:
> Thank you. Indeed, I forgot: auto f = File("outfile.txt", "w");
>
> Interestingly, this apparently works within a for-loop to overwrite the file on
> the first iteration and appending otherwise (Should there not be an explicit
> append arg?):
>
> for(int i = 0; i < 100; i++) {
> f.writefln("%s%i", "World Hello", i);
> } f.close(); // f.close outside the loop for efficiency?
>
> If someone could point me to the online documentation for this matter, I'd
> appreciate it. I'd prefer to use this forum for less elementary matters.
auto f = File("name", "options");
Creates a new File object which, based on the options, opens the file for writing (create and replace), reading (binary or text), or appending. All operations are performed on this open file until closed and reopened. So for your example if you do not wish to append to an open file you can do this
Now you can get the same behavior even if you close the File with:
for(int i = 0; i < 100; i++) {
auto f = File("name.txt", "a");
f.writefln("%s%i", "World Hello", i);
f.close();
}
Notice the "a" instead of "w" This is appending to the file when it opens it. Thus the reason the first example has f.close outside the loop is because it is opening the File outside the loop.
http://digitalmars.com/d/2.0/phobos/std_file.html
More information about the Digitalmars-d-learn
mailing list