Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Using the File's "FileMode?" attribute

Part of StandardLibraryCategory

Description

Using std.stream methods to create, read from, write to, append to, and delete a file.

Example

// streamtest.d
private import std.stream; 
private import std.stdio; 

void main() 
{ 
   // FileMode.In     - Read In 

   // FileMode.Out    - Write To 
   // FileMode.OutNew - Create \ Empty Existing 
   // FileMode.Append - Write Appending Data 
   File f = new File( r"C:\blargh.txt", FileMode.OutNew ); 
   char[] sLine1; 
   char[] sLine2; 
    
   // Creates a file or 

   // Empty the exists file 
   //f.create( r"C:\blargh.txt" ); // same as the .OutNew above 
   f.writeLine( "Bleagh!" ); 
   f.close(); 
    
   // Opens and read from the file 
   f.open( r"C:\blargh.txt", FileMode.In ); 
   sLine1 = f.readLine(); 
   f.close(); 
    
   writefln( "1st.sLine1=\"%s\"", sLine1 ); 
    
   // Append new data to the end of the file 

   f.open( r"C:\blargh.txt", FileMode.Append ); 
   f.writeLine( "Bleagh2!" ); 
   f.close(); 
  
   f.open( r"C:\blargh.txt", FileMode.In ); 
   sLine1 = f.readLine(); 
   sLine2 = f.readLine(); 
   f.close(); 
    
   writefln( "2nd.sLine1=\"%s\"", sLine1 ); 
   writefln( "2nd.sLine2=\"%s\"", sLine2 ); 
  
   // Deletes the file 
   f.remove( r"C:\blargh.txt" ); 
} 

Output

C:\dmd>bin\dmd streamtest.d 
C:\dmd\bin\..\..\dm\bin\link.exe streamtest,,,user32+kernel32/noi; 

C:\dmd>streamtest 

1st.sLine1="Bleagh!" 
2nd.sLine1="Bleagh!" 
2nd.sLine2="Bleagh2!" 

C:\dmd>

Source

Link http://www.dsource.org/tutorials/index.php?show_example=144
Posted by SpottedTiger
Date/Time Sat Feb 5, 2005 5:47 pm