27
Visual C++ Programming Penn Wu, PhD 347 Lecture #12 Basic File Handling and I/O Introduction The term basic file handling and I/Oin Visual C++ refers to various file operations including read from a file, write to a file, and enumerating files in a directory, etc. Enumerating files in a directory means to retrieve a list of the files in a directory and subdirectories. File and Stream I/O File and stream I/O (input/output) refers to the transfer of data either to or from a storage medium. A file is an ordered and named collection of bytes that has persistent storage. When you work with files, you work with directory paths, disk storage, and file and directory names. In contrast, a stream is a sequence of bytes that you can use to read from and write to a backing store, which can be one of several storage mediums (for example, disks or memory). Streams involve three fundamental operations: Reading - transferring data from a stream into a data structure, such as an array of bytes. Writing - transferring data to a stream from a data source. Seeking - querying and modifying the current position within a stream. The System::IO namespace The System::IO namespace contains types that allow reading and writing to files and data streams and types that provide basic file and directory support. To use it, you need to add the following line to the top section of the file under the other using namespace lines: using namespace System::IO; You can use the types in the System::IO namespace to interact with files and directories. For example, you can get and set properties for files and directories and retrieve collections of files and directories based on search criteria. However, you need to distinguish files and directories. Again, a file is an ordered and named collection of bytes that has persistent storage. However, a directory is container that keeps the files. Here are some commonly used file and directory classes provided by the System::IO namespace to be used in this lecture: File - provides static methods for creating, copying, deleting, moving, and opening files, and helps create a FileStream object. FileInfo - provides instance methods for creating, copying, deleting, moving, and opening files, and helps create a FileStream object. Directory - provides static methods for creating, moving, and enumerating through directories and subdirectories. DirectoryInfo - provides instance methods for creating, moving, and enumerating through directories and subdirectories. Path - provides methods and properties for processing directory strings in a cross-platform manner. The path specifies where a file or a directory physically resides. For example, “c:\temp\1.txt” specifies that a file named “1.txt” is saved under a directory named “temp” in the “C” drive. The specified path can also refer to a relative path or a Universal Naming Convention (UNC) path for a server and share name. For example, “\\MyServer\\Shared\\1.txt” means the “1.txt” of a folder named “Shared” of a server named “MyServer”. In many cases, you will need to know the name of local machine’s home drive (which is the drive the Windows operating system resides and running on and is usually the C:\ drive). You can use the GetEnvironmentVariable() method of the Environment class to retrieve the value of the Windows environment variable homedrive. System::Environment::GetEnvironmentVariable("homedrive");

file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 347

Lecture #12 Basic File Handling and I/O

Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations including

read from a file, write to a file, and enumerating files in a directory, etc. Enumerating files in a

directory means to retrieve a list of the files in a directory and subdirectories.

File and Stream

I/O

File and stream I/O (input/output) refers to the transfer of data either to or from a storage

medium. A file is an ordered and named collection of bytes that has persistent storage. When you

work with files, you work with directory paths, disk storage, and file and directory names. In

contrast, a stream is a sequence of bytes that you can use to read from and write to a backing

store, which can be one of several storage mediums (for example, disks or memory). Streams

involve three fundamental operations:

• Reading - transferring data from a stream into a data structure, such as an array of bytes.

• Writing - transferring data to a stream from a data source.

• Seeking - querying and modifying the current position within a stream.

The System::IO

namespace

The System::IO namespace contains types that allow reading and writing to files and data

streams and types that provide basic file and directory support. To use it, you need to add the

following line to the top section of the file under the other using namespace lines:

using namespace System::IO;

You can use the types in the System::IO namespace to interact with files and directories. For

example, you can get and set properties for files and directories and retrieve collections of files

and directories based on search criteria. However, you need to distinguish files and directories.

Again, a file is an ordered and named collection of bytes that has persistent storage. However, a

directory is container that keeps the files. Here are some commonly used file and directory

classes provided by the System::IO namespace to be used in this lecture:

• File - provides static methods for creating, copying, deleting, moving, and opening files, and

helps create a FileStream object.

• FileInfo - provides instance methods for creating, copying, deleting, moving, and opening

files, and helps create a FileStream object.

• Directory - provides static methods for creating, moving, and enumerating through

directories and subdirectories.

• DirectoryInfo - provides instance methods for creating, moving, and enumerating through

directories and subdirectories.

• Path - provides methods and properties for processing directory strings in a cross-platform

manner.

The path specifies where a file or a directory physically resides. For example, “c:\temp\1.txt”

specifies that a file named “1.txt” is saved under a directory named “temp” in the “C” drive. The

specified path can also refer to a relative path or a Universal Naming Convention (UNC) path for

a server and share name. For example, “\\MyServer\\Shared\\1.txt” means the “1.txt” of a folder

named “Shared” of a server named “MyServer”.

In many cases, you will need to know the name of local machine’s home drive (which is the drive

the Windows operating system resides and running on and is usually the C:\ drive). You can use

the GetEnvironmentVariable() method of the Environment class to retrieve the value of the

Windows environment variable “homedrive”.

System::Environment::GetEnvironmentVariable("homedrive");

Page 2: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 348

A sample code is:

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

using namespace System::IO;

int main()

{

String^ hd =

System::Environment::GetEnvironmentVariable("homedrive");

MessageBox::Show("Your home drive is " + hd);

}

A sample output is:

Basic File I/O In a Windows Form application, using StreamReader and StreamWriter classes of the

System::IO namespace to read from or write to files is the easiest way to handle the file I/O.

StreamReader is designed for character input in a particular encoding, whereas the Stream class

is designed for byte input and output. Use StreamReader for reading lines of information from a

standard text file. The syntax is:

StreamReader^ sr = gcnew StreamReader(path);

where path is the physical address of the file, such “c:\\temp\\1.txt”. Notice that \\ is the sequence

escape.

StreamRead uses Read() or ReadLine() method of the TextReader class to read contents from a

file.

• Read(): Reads the next character or next set of characters from the input stream.

• ReadLine(): Reads a line of characters from the current stream and returns the data as a

string.

For example, you use the following code to read contents of a text file (“C:\temp\1.txt”) in a form

that has one Label control. However, you need to make sure the C:\temp\1.txt file is currently

available.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

using namespace System::IO;

int main()

{

StreamReader^ sr = gcnew StreamReader("c:\\temp\\1.txt");

String^ line;

Page 3: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 349

String^ str;

while ( line = sr->ReadLine() )

{

str += line + "\n";

}

sr->Close();

MessageBox::Show(str);

}

It is always a good idea to close the file accessing object (e.g. sr) you created after you finishing

accessing the file. Use the Close() method to close the current reader and release any system

resources associated with the reader.

sr->Close();

There are many ways to determine when the end of the file is reached. You can re-write the

above code to the following, which use the Peek() method of TextReader class to examine the

next line before reading it. The Peek() methods returns an integer representing the next character

to be read, or -1 if no more characters are available or the stream does not support seeking.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

using namespace System::IO;

int main()

{

StreamReader^ sr = gcnew StreamReader("c:\\temp\\1.txt");

String^ str;

while ( sr->Peek() != -1 )

{

str += sr->ReadLine() + "\n";

}

sr->Close();

MessageBox::Show(str);

}

The OpenFileDialog component is a pre-configured dialog box, which is used for file selection.

You can create an instance of the StreamReader class if you prefer to work with file streams.

For example,

OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog;

.............

if (openFileDialog1->ShowDialog() ==

System::Windows::Forms::DialogResult::OK)

{

StreamReader ^ sr = gcnew StreamReader(openFileDialog1-

>FileName);

MessageBox::Show(sr->ReadToEnd());

sr->Close();

}

Page 4: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 350

Notice that the ShowDialog() method displays the dialog, and the ReadToEnd() method reads

all characters from the current position to the end.

Alternately, you can use the OpenFile() method to open the selected file. For example,

if(openFileDialog1->ShowDialog() ==

System::Windows::Forms::DialogResult::OK)

{

openFileDialog1->OpenFile();

}

The FileName property of the OpenFileDialog component can retrieve the full path of the file

being selected. For example,

String^ filePath = openFileDialog1->FileName;

StreamWriter is designed for character output in a particular Encoding, whereas classes derived

from Stream are designed for byte input and output.

StreamWriter^ sw = gcnew StreamWriter(path);

where path is the physical address of the file in UNC format, such c:\\temp\\1.txt.

StreamWriter uses either Write() or WriteLine() method of the TextWriter class to write to the

stream. For example, you can write a string “Welcome to CIS223!” to the 1.txt file using the

following code. It is necessary to note that the following code will create the c:\temp\1.txt file if

it does not exist.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

using namespace System::IO;

int main()

{

StreamWriter^ sw = gcnew StreamWriter("c:\\temp\\1.txt");

String^ line = "Welcome to CIS223!"; // message to save

sw->WriteLine(line);

sw->Close();

}

Similarly, the Close() closes the current writer and releases any system resources associated with

the writer.

The SaveFileDialog class can prompt the user to select a location for saving a file. This class

cannot be inherited. The following code example illustrates creating a SaveFileDialog, setting

members, calling the dialog box using the ShowDialog() method, and saving the current file. The

example requires a form with a button placed on it. The RestoreDirectory property gets or sets a

value indicating whether the dialog box restores the current directory before closing. The

following code also uses the FilterIndex property to set which filtering option is shown first to

the user. When the index is set to 2, as shown below, “All files (*.*) is displayed by default.

private: void button1_Click(Object^ sender, EventArgs^ e)

Page 5: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 351

{

Stream^ myStream;

SaveFileDialog^ saveFileDialog1 = gcnew SaveFileDialog;

saveFileDialog1->Filter = "txt files (*.txt)|*.txt|All files

(*.*)|*.*";

saveFileDialog1->FilterIndex = 2;

saveFileDialog1->RestoreDirectory = true;

if ( saveFileDialog1->ShowDialog() == ::DialogResult::OK )

{

if ( (myStream = saveFileDialog1->OpenFile()) != nullptr )

{

myStream->Close();

}

}

}

The Filter property gets or sets the current file name filter string, which determines the choices

that appear in the "Save as file type" or "Files of type" box in the dialog box. For each filtering

option, the filter string contains a description of the filter, followed by the vertical bar (|) and the

filter pattern. The strings for different filtering options are separated by the vertical bar. The

following is an example of a filter string:

Text files (*.txt)|*.txt|All files (*.*)|*.*

To add several filter patterns to a filter by separating the file types with semicolons, use:

Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files

(*.*)|*.*

The following code demonstrates how to save the contents of a textbox to file selected by the

SaveFileDialog class. The InitialDirectory property gets or sets the initial directory displayed

by the file dialog box.

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Windows::Forms;

using namespace System::Drawing;

using namespace System::IO;

public ref class Form1 : Form

{

TextBox^ textBox1;

public: Form1()

{

textBox1 = gcnew TextBox;

textBox1->Multiline = true;

textBox1->Width = ClientSize.Width;

textBox1->Height = 220;

Controls->Add(textBox1);

Button^ button1 = gcnew Button;

button1->Text = "Save";

button1->Location = Point(10, 230);

button1->Click += gcnew EventHandler(this,

&Form1::button1_Click);

Controls->Add(button1);

Page 6: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 352

}

private: Void button1_Click(Object^ sender, EventArgs^ e)

{

SaveFileDialog^ saveFileDialog1 = gcnew SaveFileDialog;

saveFileDialog1->Filter = "txt files (*.txt)|*.txt|All files

(*.*)|*.*";

saveFileDialog1->FilterIndex = 2;

saveFileDialog1->RestoreDirectory = true;

if ( saveFileDialog1->ShowDialog() == ::DialogResult::OK )

{

StreamWriter^ sw = gcnew StreamWriter(saveFileDialog1-

>FileName);

String^ line = textBox1->Text;

sw->WriteLine(line);

sw->Close();

MessageBox::Show("File saved as: " + saveFileDialog1-

>FileName);

}

}

};

[STAThread]

int main()

{

Application::Run(gcnew Form1);

}

A sample output looks:

and and

The pair of StringReader and StringWriter classes are similar to StreamReader and

StreamWriter except for its limitation -- strings only.

• StringReader: Implements a TextReader that reads from a string.

• StringWriter: Implements a TextWriter for writing information to a string. The information

is stored in an underlying StringBuilder.

For example, the following uses the str variable to read the three strings to the sr object (because

the sr object has the ReadLine() method). The sw object then uses the WriteLine() methods to

retrieve the string from the sr object.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

Page 7: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 353

using namespace System::Windows::Forms;

using namespace System::IO;

int main()

{

String^ str = "This is the 1st string. "

"This is the second string. "

"This is the third string.";

StringReader^ sr = gcnew StringReader(str);

StringWriter^ sw = gcnew StringWriter();

sw->WriteLine(sr->ReadLine());

MessageBox::Show(sw->ToString());

sr->Close();

sw->Close();

}

The output looks:

The following line converts the value sw holds to string and displays it in a message box.

MessageBox::Show(sw->ToString());

The File class The File Class provides static methods for the creation, copying, deletion, moving, and opening

of files, and aids in the creation of FileStream objects. Commonly used methods are:

• Copy: Copies an existing file to a new file.

• Create: Creates a file in the specified path.

• Delete: Deletes the specified file. An exception is not thrown if the specified file does not

exist.

• Exists: Determine if the given file already exists. It returns Boolean value.

• Move: Moves a specified file to a new location, providing the option to specify a new file

name.

• Open: Opens a FileStream on the specified path.

• OpenRead: Opens an existing file for reading.

• OpenWrite: Opens an existing file for writing.

As to the syntax, consider using the copy method as example:

File.Copy(sourceFileName, destFileName, overwrite);

The parameters are:

• sourceFileName: The file to copy.

• destFileName: The name of the destination file. This cannot be a directory.

• overwrite: A Boolean value (true or false) that tells if the destination file can be overwritten.

You can visit http://msdn.microsoft.com/en-us/library/system.io.file_methods.aspx for the syntax

of using these methods.

Page 8: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 354

For example, the following will check if a file “1.txt” already exists in the “C:\temp” directory. If

not, it creates one. If the “1.txt” file already exists, rename it to “2.txt”. Notice that \\ is sequence

escape.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

using namespace System::IO;

int main()

{

String^ str = "";

if (!File::Exists("c:\\temp\\1.txt"))

{

File::Create("c:\\temp\\1.txt", true);

str = "C:\\temp\\1.txt does not exist, but is created now.";

}

else

{

File::Move("c:\\temp\\1.txt", "c:\\temp\\2.txt");

str = "C:\\temp\\1.txt exist, but is renamed to

c:\\temp\\2.txt.";

}

MessageBox::Show(str);

}

The FileInfo class allows more operations such as copying, moving, renaming, creating, opening,

deleting, and appending to files. Many Visual C++ programmers prefer using the FileInfo class

over the File class, probably because some of the FileInfo methods return other I/O types when

creating or opening files. You can use these other types to further manipulate a file.

You should know several commonly used properties (they apply to both file and directory), they

are:

• Attributes: Gets or sets the FileAttributes of the current FileSystemInfo.

• CreationTime: Gets or sets the creation time of the current FileSystemInfo object.

• Extension: Gets the string representing the extension part of the file.

• FullName: Gets the full path of the directory or file.

• LastAccessTime: Gets or sets the time the current file or directory was last accessed.

• LastWriteTime: Gets or sets the time when the current file or directory was last written to.

• Length: Gets the size of the current file.

• Name: Gets the name of this DirectoryInfo instance.

The syntax of using them is:

objectID->propertyName

For example, you can use properties of the FileInfo class to retrieve information about a file. The

following use the “X:\windows\Notepad.exe” as target file.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

Page 9: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 355

using namespace System::IO;

int main()

{

String^ wd =

System::Environment::GetEnvironmentVariable("windir");

FileInfo^ fi = gcnew FileInfo(wd + "\\notepad.exe");

MessageBox::Show(fi->FullName + "\n" +

fi->CreationTime.ToString() + "\n" +

fi->LastAccessTime.ToString() + "\n" +

fi->LastWriteTime.ToString() + "\n" +

fi->Length.ToString());

}

Notice that windir is an environment variable of Microsoft Windows operating system, which is

set to the directory where WIN.COM is found. This is usually X:\WINDOWS (where X can be

C, D, E, …) in case of Windows XP and Vista. The following line will force the computer to

communicate with Windows operating systems to retrieve the current value of environment

variable “windir” and assign it to wd.

String^ wd =

System::Environment::GetEnvironmentVariable("windir");

A sample output looks:

Commonly used methods are Open, OpenRead, OpenText, CreateText, and Create. In the

following example, the FileInfo class works with the OpenText() method and the StreamReader

class to read a text file. If the file does not exist, the CreateText() method will create it.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

using namespace System::IO;

int main()

{

String^ str = "";

FileInfo^ fi = gcnew FileInfo("c:\\temp\\1.txt");

if (fi->Exists == true) {

StreamReader^ sr = fi->OpenText();

while ( sr->Peek() != -1 ) // read till the last line

{

str += sr->ReadLine() + "\n";

}

}

Page 10: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 356

else {

StreamWriter^ sw = fi->CreateText();

str = "1.txt is created!";

}

MessageBox::Show(str);

}

You can find few methods in File class compatible to those in the FileInfo class. For example,

Action File Class FileInfor Class

Append text to a file File::AppendText() FileInfo::AppendText()

Rename or move a file File::Move() FileInfo::MoveTo()

Delete a file File::Delete() FileInfo::Delete()

Copy a file File::Copy() FileInfo::CopyTo()

Microsoft provides a rough guideline as to when to use them. Basically, Because all File methods

are static, it might be more efficient to use a File method rather than a corresponding FileInfo

instance method if you want to perform only one action. All File methods require the path to the

file that you are manipulating.

The static methods of the File class perform security checks on all methods. If you are going to

reuse an object several times, consider using the corresponding instance method of FileInfo

instead, because the security check will not always be necessary.

The FileStream class can also be used to read from, write to, open, and close files on a file

system, as well as to manipulate other file-related operating system handles including pipes,

standard input, and standard output. Commonly used methods are:

• BeginRead: Begins an asynchronous read.

• BeginWrite: Begins an asynchronous write.

• Close: Closes the current stream and releases any resources (such as sockets and file

handles) associated with the current stream.

• EndRead: Waits for the pending asynchronous read to complete.

• EndWrite: Ends an asynchronous write, blocking until the I/O operation has completed.

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

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

• Seek: Sets the current position of this stream to the given value.

• Write: Writes a block of bytes to this stream using data from a buffer.

• WriteByte: Writes a byte to the current position in the file stream.

The following example uses the following syntax to read a block of bytes from the stream and

writes the data in a given buffer.

Read(byte[] array, int offset, int count)

where, the offset parameter gives the offset of the byte in array (the buffer index) at which to

begin reading, and the count parameter gives the maximum number of bytes to be read from this

stream. The returned value is the actual number of bytes read, or zero if the end of the stream is

reached. If the read operation is successful, the current position of the stream is advanced by the

number of bytes read. If an exception occurs, the current position of the stream is unchanged.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

using namespace System::IO;

Page 11: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 357

int main()

{

FileStream^ fs = gcnew FileStream("c:\\temp\\1.txt",

FileMode::Open, FileAccess::ReadWrite, FileShare::None);

array<Byte>^ b = gcnew array<Byte>(1024);

MessageBox::Show(Convert::ToString(fs->Read(b, 0, b->Length)));

}

The FileStream class also supports some methods of the File class. For example,

FileStream^ fs = File::OpenRead("c:\\temp\\1.txt");

When being used as constructor, the syntax is:

FileStream(path, FileMode, FileRAccess, FileShare, bufferSize,

options, fileSecurity)

where,

• path: A relative or absolute path for the file that the current FileStream object will

encapsulate.

• FileMode: A FileMode constant that determines how to open or create the file. Commonly

used modes are Append, Create, CreateNew, Open, and Truncate.

• FileAccess: A FileSystemRights constant that determines the access rights to use when

creating access and audit rules for the file. Commonly used file access options are

AppendData, CreateFile, CreateDirectories, Delete, Modify, Read, ReadData, Write, and

WriteData.

• FileShare: A FileShare constant that determines how the file will be shared by processes.

Commondly used options are Delete, None, Read, ReadWrite, and Write.

• bufferSize: A positive Int32 value greater than 0 indicating the buffer size. For bufferSize

values between zero and eight, the actual buffer size is set to eight bytes.

• options: A FileOptions constant that specifies additional file options.

• fileSecurity: A FileSecurity constant that determines the access control and audit security for

the file.

For example,

FileStream^ fs = gcnew FileStream("c:\\temp\\1.txt",

FileMode::Append, FileAccess::Write, FileShare::Write);

You can specify read and write operations to be either synchronous or asynchronous. The

following example opens a file or creates it if it does not already exist, and appends information

to the end of the file.

#using <System.dll>

#using <System.Windows.Forms.dll>

#include "InputBox.cpp"

using namespace System;

using namespace System::Windows::Forms;

using namespace System::IO;

int main()

{

FileStream^ fs = gcnew FileStream("c:\\temp\\1.txt",

FileMode::Append, FileAccess::Write, FileShare::Write);

Page 12: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 358

fs->Close();

String^ str = InputBox::Show("Write a paragraph:");

StreamWriter^ sw = gcnew StreamWriter("c:\\temp\\1.txt", true);

sw->Write(str);

sw->Close();

}

A sample output looks:

Check the c:\temp\1.txt to verify that the entries were saved.

The Directory

class

The Directory class is used for typical operations such as copying, moving, renaming, creating,

and deleting directories. You can also use the Directory class to get and set DateTime

information related to the creation, access, and writing of a directory. Commonly used methods

are:

• CreateDirectory: Creates all the directories in a specified path.

• Delete: Deletes a specified directory.

• Exists: Determines whether the given path refers to an existing directory on disk.

• GetDirectories: Gets the names of subdirectories in a specified directory.

• GetFiles: Returns the names of files in a specified directory.

As to the syntax, consider using the copy method as example:

Directory::Delete(path, recursive)

The parameters are:

• path: The name of the directory to remove.

• recursive: true to remove directories, subdirectories, and files in path; otherwise, false.

For example, the following checks if the “C:\tmp” directory already exists. If so, delete the entire

directory recursively.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

using namespace System::IO;

int main()

{

if (Directory::Exists("c:\\tmp"))

{

Directory::Delete("c:\\tmp", true );

MessageBox::Show("c:\\tmp is deleted.");

}

else

Page 13: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 359

{

MessageBox::Show("c:\\tmp not found.");

}

}

The Directory class and work with the Drive class to list the logical drives on a computer. For

example, you can declare a string array called drives and use the GetLogicalDrives() method to

build up its components. The Length property counts the number of components the drives array

has. The str string variable is declared and used to keep the information delivered by the

GetLogicalDrives() method.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

using namespace System::IO;

int main()

{

cli::array<String^>^ drives = Directory::GetLogicalDrives();

int dv = drives->Length;

String^ str = "Available drive(s):\n";

for (int i=0; i<dv; i++) {

str += drives[i] +"\n";

}

MessageBox::Show(str);

}

A sample output looks (note: it means the computer has C: D:, and E: logical drives):

The GetCurrentDirectory() Method can return the current working directory of the application.

For example,

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

using namespace System::IO;

int main()

{

String^ cdir = Directory::GetCurrentDirectory();

MessageBox::Show("This application is in " + cdir + "

directory.");

}

Page 14: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 360

The GetDirectories() method and GetFiles() method are also useful in obtaining a list of folders

and a list of files in the folder. For example, you can get the information about the C:\windows

directory and save the information to the C:\temp\1.txt file.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

using namespace System::IO;

int main()

{

String^ wd =

System::Environment::GetEnvironmentVariable("windir");

cli::array<String^>^ dr = Directory::GetDirectories(wd);

int n = dr->Length;

String^ str;

for (int i=0; i<n; i++) {

str += dr[i] +"\n";

}

cli::array<String^>^ files = Directory::GetFiles(wd);

int m = files->Length;

for (int i=0; i<m; i++) {

str += files[i] + "\n";

}

StreamWriter^ sw = gcnew StreamWriter( "c:\\temp\\1.txt" );

sw->WriteLine(str);

sw->Close();

MessageBox::Show("Saved on c:\\temp\\1.txt")

}

Similar to the Directory class, you can use the DirectoryInfo class for typical operations such as

copying, moving, renaming, creating, and deleting directories. This lecture then only introduces

the properties it has.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

using namespace System::IO;

int main()

{

String^ sDrive =

System::Environment::GetEnvironmentVariable("homedrive");

DirectoryInfo^ di = gcnew DirectoryInfo(sDrive + "\\MyDir");

String^ str;

if ( di->Exists ) {

str = "That path exists already.\n";

Page 15: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 361

di->Delete();

str += "But this program deleted it successfully.\n";

}

di->Create();

str += "A new "+ sDrive + "\\MyDir is just created at:\n" +

di->CreationTime;

MessageBox::Show(str);

}

The above code will create a new directory named “c:\MyDir”. A sample output looks:

The following example retrieves information about the Windows directory.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

using namespace System::IO;

int main()

{

String^ wd =

System::Environment::GetEnvironmentVariable("windir");

DirectoryInfo^ di = gcnew DirectoryInfo(wd);

MessageBox::Show(di->FullName + "\n" +

di->CreationTime + "\n" +

di->LastAccessTime + "\n" +

di->LastWriteTime );

}

A sample output looks:

BinaryWriter

and

BinaryReader

The BinaryWriter and BinaryReader classes are used for writing and reading data, rather than

character strings. They are designed to write and read primitive types in binary to a stream and

supports writing strings in a specific encoding.

Page 16: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 362

The BinaryWriter class, when being used as a constructor can initialize a new instance of the

BinaryReader class based on the supplied stream and a specific character encoding. The syntax

is:

BinaryWriter^ ObjectID = gcnew BinaryWriter(input, encoding);

where,

• input: The supplied stream.

• encoding: The character encoding.

The following code example demonstrates writing data to a new, empty file stream (1.txt). Notice

that the if statement will delete any existing file with the name “1.txt”, and recreate a blank file

named “1.txt” again. After creating the file, the associated BinaryWriter and is created, and is

used to write a list of integers (0 through 10) to 1.txt. However, the content of 1.txt is written in

the bit-stream form, and is not readable to human.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

using namespace System::IO;

int main()

{

if (File::Exists("c:\\temp\\1.txt")) {

File::Delete("c:\\temp\\1.txt");

}

FileStream^ fs = gcnew FileStream("c:\\temp\\1.txt",

FileMode::CreateNew);

// Create the writer for data.

BinaryWriter^ bw = gcnew BinaryWriter(fs);

// Write data

for (int i = 0; i < 11; i++) {

bw->Write((int) i);

}

bw->Close();

fs->Close();

}

The BinaryReader class, when being used as a constructor can initialize a new instance of the

BinaryReader class based on the supplied stream and a specific character encoding. The syntax

is:

BinaryReader^ ObjectID = gcnew BinaryReader(input, encoding);

where,

• input: The supplied stream.

• encoding: The character encoding.

The following example uses the BinaryReader to read the content of 1.txt and display them in a

message box. The ReadInt32() methods reads a 4-byte signed integer from the current stream

and advances the current position of the stream by four bytes. The BinaryReader.PeekChar()

method returns the next available character and does not advance the byte or character position.

Page 17: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 363

The value, “-1”, means no more characters are available or the stream does not support seeking.

Be sure the above 1.txt with bit-stream is created before executing the following code.

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

using namespace System::IO;

int main()

{

// Create the reader for data.

FileStream^ fs1 = gcnew FileStream("c:\\temp\\1.txt",

FileMode::Open, FileAccess::Read);

BinaryReader^ br = gcnew BinaryReader(fs1);

String^ str = "";

// Read data

while (br->PeekChar() != -1)

{

str += br->ReadInt32() + " ";

}

br->Close();

fs1->Close();

MessageBox::Show(str);

}

The output looks:

Review

Question

1. Which name space contains types that allow reading and writing to files and data streams and

types that provide basic file and directory support?

A. System

B. System::IO

C. System::Windows

D. System::Windows::Forms

2. Which is the correct way to express a path "C:\temp\2.txt" in UNC (Universal Naming

Convention) way?

A. c:\temp\2.txt

B. c:/temp/2.txt

C. C:\\temp\\2.txt

D. C://temp//2.txt

3. Which method can be used to retrieve values of Windows environment variables, such as

"homedrive"?

A. GetEnvironmentVariable()

Page 18: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 364

B. EnvironmentVariable()

C. Get()

D. GetEnvironment()

4. Which method reads the next character or next set of characters from input stream?

A. Read()

B. ReadLine

C. ReadToEnd()

D. ReadNext()

5. After initializing a StreamReader object "sr", which method can destroy the sr object?

A. sr->remove()

B. sr->Destroy()

C. sr->Delete()

D. sr->Close()

6. Which property of the FileInfo class gets the name of this FileInfo instance?

A. Name

B. FileName

C. FileInfoName

D. FileInfoObjectName

7. Given the following code segment, which statement is correct?

if (Directory::Exists("c:\\tmp")) {

Directory::Delete("c:\\tmp", true );

}

A. It checks if the “C:\tmp” directory already exists. If so, delete the entire directory recursively.

B. It checks if the “C:\tmp” directory already exists. If so, delete every files in it.

C. It checks if the “C:\tmp” directory already exists. If so, delete every sub-directory in it.

D. It deletes the “C:\tmp” directory, and then checks to make sure the deletion is completed.

8. Given the following code segment, what does the Length property do?

cli::array<String^>^ drives = Directory::GetLogicalDrives();

int dv = drives->Length;

A. It displays the total amount characters the directory name has.

B. It counts the number of files in the directory.

C. It counts the number of components the drives array has.

D. It displays each directory's name in an alphabetical order.

9. Which class is used for writing data in binary, rather than character strings?

A. FileWriter

B. StringWriter

C. StreamWriter

D. BinaryWriter

10. The __ methods reads a 4-byte signed integer from the current stream and advances the

current position of the stream by four bytes.

A. ReadInt16()

B. ReadInt32()

C. ReadInt64()

D. ReadInt128()

Page 19: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 365

Lab #12 Basic File Handling and I/O

Learning Activity #1: Creating directory and file and write to the file

1. If the C:\test directory already exists, delete it before you advance to the next step.

2. Create a directory “C:\cis223” if it does not exist.

3. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223

directory.

4. Type cd c:\cis223 and press [Enter] to change to the C:\cis223 directory.

C:\Program Files\Microsoft Visual Studio\2017\Community>cd c:\cis223

5. Type notepad lab12_1.cpp and press [Enter] to use Notepad to create a new empty file named

C:\cis223\lab12_1.cpp.

C:\cis223>notepad lab12_1.cpp

6. Enter the following codes:

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

using namespace System::IO;

int main() {

String^ sDrive = System::Environment::GetEnvironmentVariable("homedrive");

String^ msg = "";

if (!Directory::Exists(sDrive + "\\test"))

{

Directory::CreateDirectory(sDrive + "\\test");

msg += "The \'" + sDrive + "\\test\' folder is just created!\n";

}

else { msg = "The \'" + sDrive + "\\test\' folder already exists!\n"; }

if (!File::Exists(sDrive + "\\test\\1.txt"))

{

StreamWriter^ sw = File::CreateText(sDrive + "\\test\\1.txt");

sw->WriteLine("This is the first line.");

sw->WriteLine("This is the second line.");

sw->WriteLine("This is the third line.");

sw->WriteLine("This is the fourth line.");

sw->Close();

msg += "The \'" + sDrive + "\\test\\1.txt\' file is created!\n";

}

else

{

msg += "The \'" + sDrive + "\\test\\1.txt' file also exists!\n";

}

MessageBox::Show(msg);

return 0;

Page 20: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 366

}

7. Type cl /clr lab12_1.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile

the program.

C:\cis223>cl /clr lab12_1.cpp /link /subsystem:windows /ENTRY:main

8. Type lab12_1.exe and press [Enter] to test the program. It creates the X:\test (where X is usually C, but be

sure to use the correct one) directory if it does not exist.

9. It also creates a new file X:\test\1.txt with the following contents:

This is the first line.

This is the second line.

This is the third line.

This is the fourth line.

10. Find the X:\test\1.txt file and open it to verify the contents.

11. Download the “assignment template”, and rename it to lab12.doc if necessary. Capture a screen shot similar to

the above figure and paste it to the Word document named lab12.doc (or .docx).

Learning Activity #2: Reading a text file

1. Make sure the c:\test directory and c:\test\1.txt file (you had created them as product of learning activity #1)

exist.

2. In the C:\cis223 directory, use Notepad to create a new text file name “lab12_2.cpp” with the following

contents:

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

using namespace System::IO;

public ref class Form1: public Form {

Label^ label1;

public:

Form1() {

label1 = gcnew Label;

label1->Size = Drawing::Size(280,300);

label1->Location = Point(10, 10);

this->Controls->Add(label1);

this->Size = Drawing::Size(300,300);

String^ sDrive = System::Environment::GetEnvironmentVariable("homedrive");

StreamReader^ sr1 = gcnew StreamReader(sDrive +"\\test\\1.txt");

String^ line;

Page 21: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 367

label1->Text = "As long as there is a line of content, read it:\n";

while ( line = sr1->ReadLine() )

{

label1->Text += line + "\n";

}

StreamReader^ sr2 = gcnew StreamReader(sDrive +"\\test\\1.txt");

label1->Text += "\n\nUse Peek() method to check detect the last line:\n";

while ( sr2->Peek() != -1 )

{

label1->Text += sr2->ReadLine() + "\n";

}

sr1->Close();

sr2->Close();

}

};

[STAThread]

int main()

{

Application::Run(gcnew Form1);

}

3. Type cl /clr lab12_2.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile

the code.

4. Type lab12_2 and press [Enter] to test the program.

5. Capture a screen shot similar to the above figure and paste it to the Word document named lab12.doc

(or .docx).

Learning Activity #3: Creating and Writing to a text file

1. In the C:\cis223 directory, use Notepad to create a new text file name “lab12_3.cpp” with the following codes:

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Windows::Forms;

using namespace System::Drawing;

using namespace System::IO;

public ref class Form1 : Form

Page 22: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 368

{

TextBox^ textBox1;

public: Form1()

{

textBox1 = gcnew TextBox;

textBox1->Multiline = true;

textBox1->Width = ClientSize.Width;

textBox1->Height = 220;

Controls->Add(textBox1);

Button^ button1 = gcnew Button;

button1->Text = "Save";

button1->Location = Point(10, 230);

button1->Click += gcnew EventHandler(this, &Form1::button1_Click);

Controls->Add(button1);

}

private: Void button1_Click(Object^ sender, EventArgs^ e)

{

String^ sDrive = System::Environment::GetEnvironmentVariable("homedrive");

SaveFileDialog^ saveFileDialog1 = gcnew SaveFileDialog;

saveFileDialog1->InitialDirectory = sDrive;

saveFileDialog1->Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";

saveFileDialog1->FilterIndex = 2;

saveFileDialog1->RestoreDirectory = true;

if ( saveFileDialog1->ShowDialog() == ::DialogResult::OK )

{

StreamWriter^ sw = gcnew StreamWriter(saveFileDialog1->FileName);

String^ line = textBox1->Text;

sw->WriteLine(line);

sw->Close();

MessageBox::Show("File saved as: " + saveFileDialog1->FileName);

}

}

};

[STAThread]

int main()

{

Application::Run(gcnew Form1);

}

2. Type cl /clr lab12_3.cpp /link /subsystem:windows /ENTRY:main to compile the program.

3. Type lab12_3.exe and press [Enter] to launch the program.

Page 23: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 369

4. Test the program. In the textbox, type in the following paragraphs.

Water with trace amounts of radioactivity may have leaked for months from a U.S.

Navy nuclear-powered submarine as it traveled around the Pacific to ports in Guam,

Japan and Hawaii, Navy officials told CNN on Friday.

The leak was found on the USS Houston, a Los Angeles-class fast attack submarine,

after it went to Hawaii for routine maintenance last month, Navy officials said.

Just two weeks ago, thousands of Japanese protested the pending arrival of the

George Washington.

5. Click the Save button. The following pop-up window appears.

and and

6. Check if the specified text is saved.

7. Capture a screen shot similar to the above figure and paste it to the Word document named lab12.doc

(or .docx).

Learning Activity #4: Using OpenFileDialog to pick and retrieve file information

1. In the C:\cis223 directory, use Notepad to create a new text file name “lab12_4.cpp” with the following codes:

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

using namespace System::IO;

public ref class Form1: public Form {

OpenFileDialog^ openFileDialog1;

TextBox^ textBox1;

public:

Form1() {

Button^ button1 = gcnew Button;

button1->Location = Point(10, 10);

button1->Text = "Browse";

button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);

Controls->Add(button1);

textBox1 = gcnew TextBox;

textBox1->Size = Drawing::Size(260, 200);

textBox1->Location = Point(10, 50);

textBox1->Multiline = true;

Controls->Add(textBox1);

}

Page 24: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 370

private: Void button1_Click( Object^ sender, EventArgs^ e)

{

openFileDialog1 = gcnew OpenFileDialog;

if(openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK) {

String^ filePath = openFileDialog1->FileName;

FileInfo^ fi = gcnew FileInfo(filePath);

textBox1->Text = fi->FullName + Environment::NewLine +

fi->CreationTime.ToString() + Environment::NewLine +

fi->LastAccessTime.ToString() + Environment::NewLine +

fi->LastWriteTime.ToString() + Environment::NewLine +

fi->Length.ToString();

}

}

};

[STAThread]

int main()

{

Application::Run(gcnew Form1);

}

2. Type cl /clr lab12_4.cpp /link /subsystem:windows /ENTRY:main to compile the program.

3. Test the program. The following OpenFileDialog window opens::

4. Pick any file and then click Open. A message box similar to the following opens:

5. Capture a screen shot similar to the above figure and paste it to the Word document named lab12.doc

(or .docx).

Learning Activity #5: Retrieving and saving directory information

1. Make sure the X:\test directory exist, where X is the home drive.

2. Use Notepad to create a new file named lab12_5.cpp with the following contents:

Page 25: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 371

#using <System.dll>

#using <System.Windows.Forms.dll>

using namespace System;

using namespace System::Windows::Forms;

using namespace System::IO;

int main() {

String^ sDrive = System::Environment::GetEnvironmentVariable("homedrive");

StreamWriter^ sw = gcnew StreamWriter(sDrive +"\\test\\1.txt");

cli::array<String^>^ drives = Directory::GetLogicalDrives();

int dv = drives->Length;

sw->WriteLine("Your computer has the following drives:\n");

for (int i=0; i<dv; i++) {

sw->WriteLine("\t" + drives[i]);

}

sw->WriteLine(" ");

sw->WriteLine("The system drive (home drive) is: " + sDrive);

String^ wd = System::Environment::GetEnvironmentVariable("windir");

sw->WriteLine(" ");

sw->WriteLine("The system directory is: " + wd +

", and it has the following subdirectories:");

cli::array<String^>^ dr = Directory::GetDirectories(wd);

int n = dr->Length;

for (int i=0; i<n; i++) {

sw->WriteLine("\t" + dr[i]);

}

sw->WriteLine(" ");

sw->WriteLine("It also has the following files:");

cli::array<String^>^ files = Directory::GetFiles(wd);

int m = files->Length;

for (int i=0; i<m; i++) {

sw->WriteLine("\t" + files[i]);

}

sw->WriteLine(" ");

sw->Close();

String^ str;

str = "The report is saved to " + sDrive +"\\test\\1.txt";

MessageBox::Show(str);

return 0;

}

3. Compile and test the code. A sample outputs looks:

Page 26: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 372

4. A sample report looks:

5. Capture a screen shot similar to the above figure and paste it to the Word document named lab12.doc

(or .docx).

Submittal

1. Complete all the 5 learning activities and the programming exercise in this lab.

2. Create a .zip file named lab12.zip containing ONLY the following self-executable files.

• lab12_1.exe

• lab12_2.exe

• lab12_3.exe

• lab12_4.exe

• lab12_5.exe

• lab12.doc (or lab12.docx or .pdf) [You may be given zero point if this Word document is missing]

3. Log in to course web site (e.g. Canvas or Blackboard), and enter the course site.

4. Upload the zipped file to Question 11 of Assignment as response.

Programming Exercise 12:

1. Launch the Developer Command Prompt.

2. Use Notepad to create a new text file named ex12.cpp.

3. Add the following heading lines (Be sure to use replace [YourFullNameHere] with the correct one).

//File Name: ex12.cpp

//Programmer: [YourFullNameHere]

4. Write codes that will check if the C:\temp223 directory exits. If so, check whether or not a text file named

“myplan.txt” is stored under the C:\temp223 directory. If the “myplan.txt” file does not exist, you program must

create it immediately.

5. If the C:\temp223 directory does not exit, your program must be able to create the directory and then

immediately create a text file named “myplan.txt” and save it under the C:\temp223 directory.

6. Open the C:\temp223\myplan.txt file and add the following line to it. (It’s OK to overwrite the existing content).

YourFullName wrote this code.

Page 27: file stream - Cypress Collegestudents.cypresscollege.edu/cis223/lc12.pdf · Introduction The term “basic file handling and I/O” in Visual C++ refers to various file operations

Visual C++ Programming – Penn Wu, PhD 373

7. Compile the source code to produce executable code.

and

9. Download the “programming exercise template”, and rename it to ex12.doc if necessary. Copy your source

code to the file and then capture the screen shot(s) similar to the above two figures and paste it to the Word

document named “ex12.doc” (or .docx).

10. Compress the source file (ex12.cpp), executable code (ex12.exe), and Word document (ex12.doc) to a .zip file

named “ex12.zip”.

Grading criteria:

You will earn credit only when the following requirements are fulfilled. No partial credit is given.

• You successfully submit both source file and executable file.

• Your program must meet all requirements.

• Your source code must be fully functional and may not contain syntax errors in order to earn credit.

• Your executable file (program) must be executable to earn credit.

Threaded Discussion

Note: Students are required to participate in the thread discussion on a weekly basis. Student must post at

least two messages as responses to the question every week. Each message must be posted on a

different date. Grading is based on quality of the message.

Question:

Class, what is the advantage(s) or disadvantage(s) of using a "handle" while retrieving and updating

content of a file? Can Visual C++ completely eliminate the need of using a "handle" for coding

feature of file input and output? [There is never a right-or-wrong answer for this question. Please free

feel to express your opinion.]

Be sure to use proper college level of writing. Do not use texting language.