| 1 | = Using the File's "FileMode" attribute = |
---|
| 2 | |
---|
| 3 | ''Part of'' StandardLibraryCategory |
---|
| 4 | |
---|
| 5 | == Description == |
---|
| 6 | |
---|
| 7 | Using std.stream methods to create, read from, write to, append to, and delete a file. |
---|
| 8 | |
---|
| 9 | == Example == |
---|
| 10 | |
---|
| 11 | {{{ |
---|
| 12 | #!d |
---|
| 13 | // streamtest.d |
---|
| 14 | private import std.stream; |
---|
| 15 | private import std.stdio; |
---|
| 16 | |
---|
| 17 | void main() |
---|
| 18 | { |
---|
| 19 | // FileMode.In - Read In |
---|
| 20 | |
---|
| 21 | // FileMode.Out - Write To |
---|
| 22 | // FileMode.OutNew - Create \ Empty Existing |
---|
| 23 | // FileMode.Append - Write Appending Data |
---|
| 24 | File f = new File( r"C:\blargh.txt", FileMode.OutNew ); |
---|
| 25 | char[] sLine1; |
---|
| 26 | char[] sLine2; |
---|
| 27 | |
---|
| 28 | // Creates a file or |
---|
| 29 | |
---|
| 30 | // Empty the exists file |
---|
| 31 | //f.create( r"C:\blargh.txt" ); // same as the .OutNew above |
---|
| 32 | f.writeLine( "Bleagh!" ); |
---|
| 33 | f.close(); |
---|
| 34 | |
---|
| 35 | // Opens and read from the file |
---|
| 36 | f.open( r"C:\blargh.txt", FileMode.In ); |
---|
| 37 | sLine1 = f.readLine(); |
---|
| 38 | f.close(); |
---|
| 39 | |
---|
| 40 | writefln( "1st.sLine1=\"%s\"", sLine1 ); |
---|
| 41 | |
---|
| 42 | // Append new data to the end of the file |
---|
| 43 | |
---|
| 44 | f.open( r"C:\blargh.txt", FileMode.Append ); |
---|
| 45 | f.writeLine( "Bleagh2!" ); |
---|
| 46 | f.close(); |
---|
| 47 | |
---|
| 48 | f.open( r"C:\blargh.txt", FileMode.In ); |
---|
| 49 | sLine1 = f.readLine(); |
---|
| 50 | sLine2 = f.readLine(); |
---|
| 51 | f.close(); |
---|
| 52 | |
---|
| 53 | writefln( "2nd.sLine1=\"%s\"", sLine1 ); |
---|
| 54 | writefln( "2nd.sLine2=\"%s\"", sLine2 ); |
---|
| 55 | |
---|
| 56 | // Deletes the file |
---|
| 57 | f.remove( r"C:\blargh.txt" ); |
---|
| 58 | } |
---|
| 59 | }}} |
---|
| 60 | |
---|
| 61 | == Output == |
---|
| 62 | |
---|
| 63 | {{{ |
---|
| 64 | C:\dmd>bin\dmd streamtest.d |
---|
| 65 | C:\dmd\bin\..\..\dm\bin\link.exe streamtest,,,user32+kernel32/noi; |
---|
| 66 | |
---|
| 67 | C:\dmd>streamtest |
---|
| 68 | |
---|
| 69 | 1st.sLine1="Bleagh!" |
---|
| 70 | 2nd.sLine1="Bleagh!" |
---|
| 71 | 2nd.sLine2="Bleagh2!" |
---|
| 72 | |
---|
| 73 | C:\dmd> |
---|
| 74 | }}} |
---|
| 75 | |
---|
| 76 | == Source == |
---|
| 77 | |
---|
| 78 | || Link || http://www.dsource.org/tutorials/index.php?show_example=144 || |
---|
| 79 | || Posted by || !SpottedTiger || |
---|
| 80 | || Date/Time || Sat Feb 5, 2005 5:47 pm || |