Which of the following statements opens a file and link it to a file stream object in C++?


Next: Reading and Writing Text Up: File I/O Previous: File I/O

In C++, a file is opened by linking it to a stream. There are three types of streams: input, output and input/output. To open an input stream you must declare the stream to be of class ifstream. To open an output stream, it must be declared as class ofstream. A stream that will be be performing both input and output operations must be declared as class fstream. For example, this fragment creates one input stream, one output stream and one stream that is capable of both input and output.

ifstream in;
ofstream out;
fstream both;

Once you have created s stream, one way to associate it with a file is by using open[]. This function is a member of each of the three stream classes. Its prototype is shown here

void open[const char *filename, int mode, int access];

Here, filename is the name of the file. The value of the mode determines how the file is opened. It must be one or more of the following values which are defined in the fstream.h

ios::app // causes all output to the file to be appended to the end
ios::ate // causes a seek to the end of the file occur when file is opened
ios::binary// causes a file to be opened in binary mode
ios::out // specifies that the file is capable of output
ios::in// specifies that the file is capable of input
ios::nocreate// causes open[] to fail if the file doe not already exist.
ios::noreplace// causes open[] to fail if the file already exist
ios::trunc// causes the contents of a preexisting file by the same name to be destroyed and truncate the file to zero length

The value of access determines how the file can be accessed. In DOS/Windows environments, this value generally corresponds to the DOS/Windows file attribute code listed here:

Attribute Meaning
  Norma file; open access
1 read-only file
2 hidden file
4 system file
8 archive bit set

The following fragment opens a normal output file

ofstream out;
out.open["test",ios::out,o];

The default value for mode is ios::out for ofstream and ios::in for ifstream and the default value for access is 0. Hence the previous statement can be written as

out.open["test"];

To open a stream for input and output, you must specify both ios::in and ios::out mode values as shown here,

fstream xyst;
xyst.open["test",ios::in | ios::out];

To close a file, use the member function close[]. For example to close the file linked to a stream called xyst you would use this statement

xyst.close[];
The close function takes no parameters and returns no values.


Next: Reading and Writing Text Up: File I/O Previous: File I/O Yousef Haik
2/23/1998

Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

FileStream Class

  • Reference

Definition

Provides a Stream for a file, supporting both synchronous and asynchronous read and write operations.

In this article

public ref class FileStream : System::IO::Stream public class FileStream : System.IO.Stream[System.Runtime.InteropServices.ComVisible[true]] public class FileStream : System.IO.Streamtype FileStream = class inherit Stream[] type FileStream = class inherit StreamPublic Class FileStream Inherits StreamInheritanceInheritanceDerivedAttributes

Examples

The following example demonstrates some of the FileStream constructors.

using namespace System; using namespace System::IO; using namespace System::Text; void AddText[ FileStream^ fs, String^ value ] { array^info = [gcnew UTF8Encoding[ true ]]->GetBytes[ value ]; fs->Write[ info, 0, info->Length ]; } int main[] { String^ path = "c:\\temp\\MyTest.txt"; // Delete the file if it exists. if [ File::Exists[ path ] ] { File::Delete[ path ]; } //Create the file. { FileStream^ fs = File::Create[ path ]; try { AddText[ fs, "This is some text" ]; AddText[ fs, "This is some more text," ]; AddText[ fs, "\r\nand this is on a new line" ]; AddText[ fs, "\r\n\r\nThe following is a subset of characters:\r\n" ]; for [ int i = 1; i < 120; i++ ] { AddText[ fs, Convert::ToChar[ i ].ToString[] ]; //Split the output at every 10th character. if [ Math::IEEERemainder[ Convert::ToDouble[ i ], 10 ] == 0 ] { AddText[ fs, "\r\n" ]; } } } finally { if [ fs ] delete [IDisposable^]fs; } } //Open the stream and read it back. { FileStream^ fs = File::OpenRead[ path ]; try { array^b = gcnew array[1024]; UTF8Encoding^ temp = gcnew UTF8Encoding[ true ]; while [ fs->Read[ b, 0, b->Length ] > 0 ] { Console::WriteLine[ temp->GetString[ b ] ]; } } finally { if [ fs ] delete [IDisposable^]fs; } } } using System; using System.IO; using System.Text; class Test { public static void Main[] { string path = @"c:\temp\MyTest.txt"; // Delete the file if it exists. if [File.Exists[path]] { File.Delete[path]; } //Create the file. using [FileStream fs = File.Create[path]] { AddText[fs, "This is some text"]; AddText[fs, "This is some more text,"]; AddText[fs, "\r\nand this is on a new line"]; AddText[fs, "\r\n\r\nThe following is a subset of characters:\r\n"]; for [int i=1;i < 120;i++] { AddText[fs, Convert.ToChar[i].ToString[]]; } } //Open the stream and read it back. using [FileStream fs = File.OpenRead[path]] { byte[] b = new byte[1024]; UTF8Encoding temp = new UTF8Encoding[true]; while [fs.Read[b,0,b.Length] > 0] { Console.WriteLine[temp.GetString[b]]; } } } private static void AddText[FileStream fs, string value] { byte[] info = new UTF8Encoding[true].GetBytes[value]; fs.Write[info, 0, info.Length]; } } Imports System.IO Imports System.Text Public Class Test Public Shared Sub Main[] Dim path As String = "c:\temp\MyTest.txt" ' Delete the file if it exists. If File.Exists[path] Then File.Delete[path] End If 'Create the file. Dim fs As FileStream = File.Create[path] AddText[fs, "This is some text"] AddText[fs, "This is some more text,"] AddText[fs, Environment.NewLine & "and this is on a new line"] AddText[fs, Environment.NewLine & Environment.NewLine] AddText[fs, "The following is a subset of characters:" & Environment.NewLine] Dim i As Integer For i = 1 To 120 AddText[fs, Convert.ToChar[i].ToString[]] Next fs.Close[] 'Open the stream and read it back. fs = File.OpenRead[path] Dim b[1023] As Byte Dim temp As UTF8Encoding = New UTF8Encoding[True] Do While fs.Read[b, 0, b.Length] > 0 Console.WriteLine[temp.GetString[b]] Loop fs.Close[] End Sub Private Shared Sub AddText[ByVal fs As FileStream, ByVal value As String] Dim info As Byte[] = New UTF8Encoding[True].GetBytes[value] fs.Write[info, 0, info.Length] End Sub End Class

The following example shows how to write to a file asynchronously. This code runs in a WPF app that has a TextBlock named UserInput and a button hooked up to a Click event handler that is named Button_Click. The file path needs to be changed to a file that exists on the computer.

using System; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.IO; namespace WpfApplication1 { public partial class MainWindow : Window { public MainWindow[] { InitializeComponent[]; } private async void Button_Click[object sender, RoutedEventArgs e] { UnicodeEncoding uniencoding = new UnicodeEncoding[]; string filename = @"c:\Users\exampleuser\Documents\userinputlog.txt"; byte[] result = uniencoding.GetBytes[UserInput.Text]; using [FileStream SourceStream = File.Open[filename, FileMode.OpenOrCreate]] { SourceStream.Seek[0, SeekOrigin.End]; await SourceStream.WriteAsync[result, 0, result.Length]; } } } } Imports System.IO Imports System.Text Class MainWindow Private Async Sub Button_Click[sender As Object, e As RoutedEventArgs] Dim uniencoding As UnicodeEncoding = New UnicodeEncoding[] Dim filename As String = "c:\Users\exampleuser\Documents\userinputlog.txt" Dim result As Byte[] = uniencoding.GetBytes[UserInput.Text] Using SourceStream As FileStream = File.Open[filename, FileMode.OpenOrCreate] SourceStream.Seek[0, SeekOrigin.End] Await SourceStream.WriteAsync[result, 0, result.Length] End Using End Sub End Class

Remarks

Use the FileStream class to read from, write to, open, and close files on a file system, and to manipulate other file-related operating system handles, including pipes, standard input, and standard output. You can use the Read, Write, CopyTo, and Flush methods to perform synchronous operations, or the ReadAsync, WriteAsync, CopyToAsync, and FlushAsync methods to perform asynchronous operations. Use the asynchronous methods to perform resource-intensive file operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. FileStream buffers input and output for better performance.

Important

This type implements the IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its Dispose method in a try/catch block. To dispose of it indirectly, use a language construct such as using [in C#] or Using [in Visual Basic]. For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

The IsAsync property detects whether the file handle was opened asynchronously. You specify this value when you create an instance of the FileStream class using a constructor that has an isAsync, useAsync, or options parameter. When the property is true, the stream utilizes overlapped I/O to perform file operations asynchronously. However, the IsAsync property does not have to be true to call the ReadAsync, WriteAsync, or CopyToAsync method. When the IsAsync property is false and you call the asynchronous read and write operations, the UI thread is still not blocked, but the actual I/O operation is performed synchronously.

The Seek method supports random access to files. Seek allows the read/write position to be moved to any position within the file. This is done with byte offset reference point parameters. The byte offset is relative to the seek reference point, which can be the beginning, the current position, or the end of the underlying file, as represented by the three members of the SeekOrigin enumeration.

Note

Disk files always support random access. At the time of construction, the CanSeek property value is set to true or false depending on the underlying file type. If the underlying file type is FILE_TYPE_DISK, as defined in winbase.h, the CanSeek property value is true. Otherwise, the CanSeek property value is false.

If a process terminates with part of a file locked or closes a file that has outstanding locks, the behavior is undefined.

For directory operations and other file operations, see the File, Directory, and Path classes. The File class is a utility class that has static methods primarily for the creation of FileStream objects based on file paths. The MemoryStream class creates a stream from a byte array and is similar to the FileStream class.

For a list of common file and directory operations, see Common I/O Tasks.

Detection of Stream Position Changes

When a FileStream object does not have an exclusive hold on its handle, another thread could access the file handle concurrently and change the position of the operating system's file pointer that is associated with the file handle. In this case, the cached position in the FileStream object and the cached data in the buffer could be compromised. The FileStream object routinely performs checks on methods that access the cached buffer to ensure that the operating system's handle position is the same as the cached position used by the FileStream object.

If an unexpected change in the handle position is detected in a call to the Read method, the .NET Framework discards the contents of the buffer and reads the stream from the file again. This can affect performance, depending on the size of the file and any other processes that could affect the position of the file stream.

If an unexpected change in the handle position is detected in a call to the Write method, the contents of the buffer are discarded and an IOException exception is thrown.

A FileStream object will not have an exclusive hold on its handle when either the SafeFileHandle property is accessed to expose the handle or the FileStream object is given the SafeFileHandle property in its constructor.

Constructors

FileStream[IntPtr, FileAccess]

Obsolete.

Obsolete.

Obsolete.

Obsolete.

Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission.

FileStream[IntPtr, FileAccess, Boolean]

Obsolete.

Obsolete.

Obsolete.

Obsolete.

Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission and FileStream instance ownership.

FileStream[IntPtr, FileAccess, Boolean, Int32]

Obsolete.

Obsolete.

Obsolete.

Obsolete.

Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, FileStream instance ownership, and buffer size.

FileStream[IntPtr, FileAccess, Boolean, Int32, Boolean]

Obsolete.

Obsolete.

Obsolete.

Obsolete.

Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, FileStream instance ownership, buffer size, and synchronous or asynchronous state.

FileStream[SafeFileHandle, FileAccess]

Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission.

FileStream[SafeFileHandle, FileAccess, Int32]

Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, and buffer size.

FileStream[SafeFileHandle, FileAccess, Int32, Boolean]

Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, buffer size, and synchronous or asynchronous state.

FileStream[String, FileMode]

Initializes a new instance of the FileStream class with the specified path and creation mode.

FileStream[String, FileMode, FileAccess]

Initializes a new instance of the FileStream class with the specified path, creation mode, and read/write permission.

FileStream[String, FileMode, FileAccess, FileShare]

Initializes a new instance of the FileStream class with the specified path, creation mode, read/write permission, and sharing permission.

FileStream[String, FileMode, FileAccess, FileShare, Int32]

Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, and buffer size.

FileStream[String, FileMode, FileAccess, FileShare, Int32, Boolean]

Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, buffer size, and synchronous or asynchronous state.

FileStream[String, FileMode, FileAccess, FileShare, Int32, FileOptions]

Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, the access other FileStreams can have to the same file, the buffer size, and additional file options.

FileStream[String, FileMode, FileSystemRights, FileShare, Int32, FileOptions]

Initializes a new instance of the FileStream class with the specified path, creation mode, access rights and sharing permission, the buffer size, and additional file options.

FileStream[String, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity]

Initializes a new instance of the FileStream class with the specified path, creation mode, access rights and sharing permission, the buffer size, additional file options, access control and audit security.

FileStream[String, FileStreamOptions]

Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, buffer size, additional file options, preallocation size, and the access other FileStreams can have to the same file.

Properties

CanRead

Gets a value that indicates whether the current stream supports reading.

CanSeek

Gets a value that indicates whether the current stream supports seeking.

CanTimeout

Gets a value that determines whether the current stream can time out.

[Inherited from Stream]
CanWrite

Gets a value that indicates whether the current stream supports writing.

Handle

Obsolete.

Obsolete.

Obsolete.

Obsolete.

Gets the operating system file handle for the file that the current FileStream object encapsulates.

IsAsync

Gets a value that indicates whether the FileStream was opened asynchronously or synchronously.

Length

Gets the length in bytes of the stream.

Name

Gets the absolute path of the file opened in the FileStream.

Position

Gets or sets the current position of this stream.

ReadTimeout

Gets or sets a value, in milliseconds, that determines how long the stream will attempt to read before timing out.

[Inherited from Stream]
SafeFileHandle

Gets a SafeFileHandle object that represents the operating system file handle for the file that the current FileStream object encapsulates.

WriteTimeout

Gets or sets a value, in milliseconds, that determines how long the stream will attempt to write before timing out.

[Inherited from Stream]

Methods

BeginRead[Byte[], Int32, Int32, AsyncCallback, Object]

Begins an asynchronous read operation. Consider using ReadAsync[Byte[], Int32, Int32, CancellationToken] instead.

BeginRead[Byte[], Int32, Int32, AsyncCallback, Object]

Begins an asynchronous read operation. [Consider using ReadAsync[Byte[], Int32, Int32] instead.]

[Inherited from Stream]
BeginWrite[Byte[], Int32, Int32, AsyncCallback, Object]

Begins an asynchronous write operation. Consider using WriteAsync[Byte[], Int32, Int32, CancellationToken] instead.

BeginWrite[Byte[], Int32, Int32, AsyncCallback, Object]

Begins an asynchronous write operation. [Consider using WriteAsync[Byte[], Int32, Int32] instead.]

[Inherited from Stream]
Close[]

Closes the current stream and releases any resources [such as sockets and file handles] associated with the current stream.

Close[]

Closes the current stream and releases any resources [such as sockets and file handles] associated with the current stream. Instead of calling this method, ensure that the stream is properly disposed.

[Inherited from Stream]
CopyTo[Stream]

Reads the bytes from the current stream and writes them to another stream. Both streams positions are advanced by the number of bytes copied.

[Inherited from Stream]
CopyTo[Stream, Int32]

Reads the bytes from the current stream and writes them to another stream, using a specified buffer size. Both streams positions are advanced by the number of bytes copied.

[Inherited from Stream]
CopyToAsync[Stream]

Asynchronously reads the bytes from the current stream and writes them to another stream. Both streams positions are advanced by the number of bytes copied.

[Inherited from Stream]
CopyToAsync[Stream, CancellationToken]

Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified cancellation token. Both streams positions are advanced by the number of bytes copied.

[Inherited from Stream]
CopyToAsync[Stream, Int32]

Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size. Both streams positions are advanced by the number of bytes copied.

[Inherited from Stream]
CopyToAsync[Stream, Int32, CancellationToken]

Asynchronously reads the bytes from the current file stream and writes them to another stream, using a specified buffer size and cancellation token.

CopyToAsync[Stream, Int32, CancellationToken]

Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size and cancellation token. Both streams positions are advanced by the number of bytes copied.

[Inherited from Stream]
CreateObjRef[Type]

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

[Inherited from MarshalByRefObject]
CreateWaitHandle[]

Obsolete.

Obsolete.

Obsolete.

Allocates a WaitHandle object.

[Inherited from Stream]
Dispose[]

Releases all resources used by the Stream.

[Inherited from Stream]
Dispose[Boolean]

Releases the unmanaged resources used by the FileStream and optionally releases the managed resources.

DisposeAsync[]

Asynchronously releases the unmanaged resources used by the FileStream.

DisposeAsync[]

Asynchronously releases the unmanaged resources used by the Stream.

[Inherited from Stream]
EndRead[IAsyncResult]

Waits for the pending asynchronous read operation to complete. [Consider using ReadAsync[Byte[], Int32, Int32, CancellationToken] instead.]

EndRead[IAsyncResult]

Waits for the pending asynchronous read to complete. [Consider using ReadAsync[Byte[], Int32, Int32] instead.]

[Inherited from Stream]
EndWrite[IAsyncResult]

Ends an asynchronous write operation and blocks until the I/O operation is complete. [Consider using WriteAsync[Byte[], Int32, Int32, CancellationToken] instead.]

EndWrite[IAsyncResult]

Ends an asynchronous write operation. [Consider using WriteAsync[Byte[], Int32, Int32] instead.]

[Inherited from Stream]
Equals[Object]

Determines whether the specified object is equal to the current object.

[Inherited from Object]
Finalize[]

Ensures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the FileStream.

Flush[]

Clears buffers for this stream and causes any buffered data to be written to the file.

Flush[Boolean]

Clears buffers for this stream and causes any buffered data to be written to the file, and also clears all intermediate file buffers.

FlushAsync[]

Asynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device.

[Inherited from Stream]
FlushAsync[CancellationToken]

Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests.

FlushAsync[CancellationToken]

Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests.

[Inherited from Stream]
GetAccessControl[]

Gets a FileSecurity object that encapsulates the access control list [ACL] entries for the file described by the current FileStream object.

GetHashCode[]

Serves as the default hash function.

[Inherited from Object]
GetLifetimeService[]

Obsolete.

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[]

Obsolete.

Obtains a lifetime service object to control the lifetime policy for this instance.

[Inherited from MarshalByRefObject]
Lock[Int64, Int64]

Prevents other processes from reading from or writing to the FileStream.

MemberwiseClone[]

Creates a shallow copy of the current Object.

[Inherited from Object]
MemberwiseClone[Boolean]

Creates a shallow copy of the current MarshalByRefObject object.

[Inherited from MarshalByRefObject]
ObjectInvariant[]

Obsolete.

Provides support for a Contract.

[Inherited from Stream]
Read[Byte[], Int32, Int32]

Reads a block of bytes from the stream and writes the data in a given buffer.

Read[Span]

Reads a sequence of bytes from the current file stream and advances the position within the file stream by the number of bytes read.

Read[Span]

When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

[Inherited from Stream]
ReadAsync[Byte[], Int32, Int32]

Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

[Inherited from Stream]
ReadAsync[Byte[], Int32, Int32, CancellationToken]

Asynchronously reads a sequence of bytes from the current file stream and writes them to a byte array beginning at a specified offset, advances the position within the file stream by the number of bytes read, and monitors cancellation requests.

ReadAsync[Byte[], Int32, Int32, CancellationToken]

Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

[Inherited from Stream]
ReadAsync[Memory, CancellationToken]

Asynchronously reads a sequence of bytes from the current file stream and writes them to a memory region, advances the position within the file stream by the number of bytes read, and monitors cancellation requests.

ReadAsync[Memory, CancellationToken]

Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

[Inherited from Stream]
ReadAtLeast[Span, Int32, Boolean]

Reads at least a minimum number of bytes from the current stream and advances the position within the stream by the number of bytes read.

[Inherited from Stream]
ReadAtLeastAsync[Memory, Int32, Boolean, CancellationToken]

Asynchronously reads at least a minimum number of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

[Inherited from Stream]
ReadByte[]

Reads a byte from the file and advances the read position one byte.

ReadExactly[Byte[], Int32, Int32]

Reads count number of bytes from the current stream and advances the position within the stream.

[Inherited from Stream]
ReadExactly[Span]

Reads bytes from the current stream and advances the position within the stream until the buffer is filled.

[Inherited from Stream]
ReadExactlyAsync[Byte[], Int32, Int32, CancellationToken]

Asynchronously reads count number of bytes from the current stream, advances the position within the stream, and monitors cancellation requests.

[Inherited from Stream]
ReadExactlyAsync[Memory, CancellationToken]

Asynchronously reads bytes from the current stream, advances the position within the stream until the buffer is filled, and monitors cancellation requests.

[Inherited from Stream]
Seek[Int64, SeekOrigin]

Sets the current position of this stream to the given value.

SetAccessControl[FileSecurity]

Applies access control list [ACL] entries described by a FileSecurity object to the file described by the current FileStream object.

SetLength[Int64]

Sets the length of this stream to the given value.

ToString[]

Returns a string that represents the current object.

[Inherited from Object]
Unlock[Int64, Int64]

Allows access by other processes to all or part of a file that was previously locked.

Write[Byte[], Int32, Int32]

Writes a block of bytes to the file stream.

Write[ReadOnlySpan]

Writes a sequence of bytes from a read-only span to the current file stream and advances the current position within this file stream by the number of bytes written.

Write[ReadOnlySpan]

When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

[Inherited from Stream]
WriteAsync[Byte[], Int32, Int32]

Asynchronously writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

[Inherited from Stream]
WriteAsync[Byte[], Int32, Int32, CancellationToken]

Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.

WriteAsync[Byte[], Int32, Int32, CancellationToken]

Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.

[Inherited from Stream]
WriteAsync[ReadOnlyMemory, CancellationToken]

Asynchronously writes a sequence of bytes from a memory region to the current file stream, advances the current position within this file stream by the number of bytes written, and monitors cancellation requests.

WriteAsync[ReadOnlyMemory, CancellationToken]

Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.

[Inherited from Stream]
WriteByte[Byte]

Writes a byte to the current position in the file stream.

Explicit Interface Implementations

Extension Methods

GetAccessControl[FileStream]

Returns the security information of a file.

SetAccessControl[FileStream, FileSecurity]

Changes the security attributes of an existing file.

AsInputStream[Stream]

Converts a managed stream in the .NET for Windows Store apps to an input stream in the Windows Runtime.

AsOutputStream[Stream]

Converts a managed stream in the .NET for Windows Store apps to an output stream in the Windows Runtime.

AsRandomAccessStream[Stream]

Converts the specified stream to a random access stream.

ConfigureAwait[IAsyncDisposable, Boolean]

Configures how awaits on the tasks returned from an async disposable are performed.

Applies to

See also

  • File
  • FileAccess
  • FileMode
  • FileShare
  • File and Stream I/O
  • How to: Read Text from a File
  • How to: Write Text to a File
  • How to: Read and Write to a Newly Created Data File

Which of the following statements opens a file and link it to a file stream object in C++?

Opening a File And ifstream object is used to open a file for reading purpose only. Following is the standard syntax for open[] function, which is a member of fstream, ifstream, and ofstream objects. void open[const char *filename, ios::openmode mode];

Which of the following opens the file associated with the stream in C?

The fopen function opens a stream for I/O to the file filename , and returns a pointer to the stream. The opentype argument is a string that controls how the file is opened and specifies attributes of the resulting stream.

Which function links a stream to a file?

Having created a stream, we can connect it to a file using the member function "open[...]".

Which of the following opens the file associated with the stream select one?

Explanation: By default, the file is opened in ios::out mode if the file object we are using is of ofstream class.

Chủ Đề