< C++ .NET System::IO - Files 2 | Main | C++ .NET System::IO - Files 4 >


 

 

Working with Files 3

 

 

What we have in this page?

  1. The FileStream Class

  2. Using TextReader

 

 

The FileStream Class

 

FileStream is used to pass bytes from some other class such as StreamWriter to a file. There are several overloaded constructors to this class that let you specify combinations of the following:

 

 

The file mode is represented by members of the FileMode enumeration, which are described in the following table.

 

 

 

 

Member name

Description

Append

Opens the file if it exists and seeks to the end of the file, or creates a new file. FileMode::Append can only be used in conjunction with FileAccess::Write. Any attempt to read fails and throws an ArgumentException.

Create

Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This requires FileIOPermissionAccess::Write. System::IO::FileMode::Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate.

CreateNew

Specifies that the operating system should create a new file. This requires FileIOPermissionAccess::Write. If the file already exists, an IOException is thrown.

Open

Specifies that the operating system should open an existing file. The ability to open the file is dependent on the value specified by FileAccess. A System::IO::FileNotFoundException is thrown if the file does not exist.

OpenOrCreate

Specifies that the operating system should open a file if it exists; otherwise, a new file should be created. If the file is opened with FileAccess::Read, FileIOPermissionAccess::Read is required. If the file access is FileAccess::Write or FileAccess::ReadWrite, FileIOPermissionAccess::Write is required. If the file access is FileAccess::Append, then FileIOPermissionAccess::Append is required.

Truncate

Specifies that the operating system should open an existing file. Once opened, the file should be truncated so that its size is zero bytes. This requires FileIOPermissionAccess.Write. Attempts to read from a file opened with Truncate cause an exception.

 

Table 6

 

The access is represented by members of the FileAccess enumeration, as listed in the following table.

 

Member

Description

Read

Read access to the file. Data can be read from the file. Combine with Write for read/write access.

ReadWrite

Read and Write access to the file. Data can be written to and read from the file.

Write

Write access to the file. Data can be written to the file. Combine with Read for read/write access.

 

Table 7

 

Similarly, the sharing access is specified by the FileShare enumeration, as listed in the following table.

 

Member name

Description

Delete

Allows subsequent deleting of a file.

Inheritable

Makes the file handle inheritable by child processes. This is not directly supported by Win32.

None

Declines sharing of the current file. Any request to open the file (by this process or another process) will fail until the file is closed.

Read

Allows subsequent opening of the file for reading. If this flag is not specified, any request to open the file for reading (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.

ReadWrite

Allows subsequent opening of the file for reading or writing. If this flag is not specified, any request to open the file for reading or writing (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.

Write

Allows subsequent opening of the file for writing. If this flag is not specified, any request to open the file for writing (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.

 

Table 8

 

The following code snippet example shows how to construct a FileStream using these permissions:

FileStream^ fs2 = gcnew FileStream(

   L"foo.txt",              // the filename

    FileMode::Create,       // create or overwrite

    FileAccess::ReadWrite,  // request read/write access

    FileShare::Read);       // allow shared reading

The following code example shows how to write data to a file, byte by byte, and then verify that the data was written correctly.

// Testprog.cpp : main project file.

// Console mode application with /clr

 

#include "stdafx.h"

 

using namespace System;

using namespace System::IO;

 

int main(array<System::String ^> ^args)

{

      // file name...

      String^ fileName =  "Test@##@.dat";

 

      // Create random data to write to the file.

      array<Byte>^dataArray = gcnew array<Byte>(1000);

     

      (gcnew Random)->NextBytes(dataArray);

     

      FileStream^ fileStream = gcnew FileStream(fileName,FileMode::Create);

      try

      {

            // Write the data to the file, byte by byte.

            for (int i = 0; i < dataArray->Length; i++)

            {

                  fileStream->WriteByte(dataArray[i]);

            }

            // Set the stream position to the beginning of the file.

            fileStream->Seek(0, SeekOrigin::Begin);

            // Read and verify the data.

            for (int i = 0; i < fileStream->Length; i++)

            {

                  if (dataArray[i] != fileStream->ReadByte())

                  {

                        Console::WriteLine("Error writing data.");

                        return  -1;

                  }

            }

            Console::WriteLine("The data was written to {0} \n"

      "and verified.", fileStream->Name);

   }

   finally

   {

      fileStream->Close();

   }

   return 0;

}

Output:

 

 

 

 

------------------------------------------------------------

Code example shows how to write data to a file, byte by byte, and then verify that the data was written correctly

 

Although you’ll usually use the FileStream class with other writer classes, you can use its Read and Write methods to input and output bytes directly.

 

Using TextReader

 

The structure and operation of the TextReader class parallels that of TextWriter. The following table lists the methods provided for you by TextReader.

 

Public Methods

Name

Description

Symbol

Public method

Close

Closes the TextReader and releases any system resources associated with the TextReader.

CreateObjRef

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)

Dispose

Overloaded. Releases all resources used by the TextReader object.

Equals

Overloaded. Determines whether two Object instances are equal. (Inherited from Object.)

GetHashCode

Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)

GetLifetimeService

Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)

GetType

Gets the Type of the current instance. (Inherited from Object.)

InitializeLifetimeService

Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)

Peek

Reads the next character without changing the state of the reader or the character source. Returns the next available character without actually reading it from the input stream.

Read

Overloaded. Reads data from an input stream.

ReadBlock

Reads a maximum of count characters from the current stream and writes the data to buffer, beginning at index.

ReadLine

Reads a line of characters from the current stream and returns the data as a string.

ReadToEnd

Reads all characters from the current position to the end of the TextReader and returns them as one string.

ReferenceEquals

Determines whether the specified Object instances are the same instance. (Inherited from Object.)

Synchronized

Creates a thread-safe wrapper around the specified TextReader.

ToString

Returns a String that represents the current Object. (Inherited from Object.)

 

Table 9

 

 

 

 

Protected Methods

Name

Description

Symbol

Protected method

Dispose

Overloaded. Releases all resources used by the TextReader object.

Finalize

Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)

MemberwiseClone

Overloaded. (Inherited from MarshalByRefObject.)

 

Table 10

 

As with TextWriter, you use TextReader by plugging a reader into an object that is going to act as a source of bytes. There are several of these, including the one you’ve already met, FileStream.

 

 

Part 1 | Part 2 | Part 3 | Part 4 | Part 5 | Part 6 | Part 7

 

 


< C++ .NET System::IO - Files 2 | Main | C++ .NET System::IO - Files 4 >