How to do basic file I/O in Visual C++ 2005 or in Visual C++ 2008

How to do basic file I/O in Visual C++ 2005 or in Visual C++ 2008
Article ID : 950617
Last Review : April 2, 2008
Revision : 1.0
For a Managed Extensions for C++ version of this article, see 307398 (/Feedback.aspx?kbNumber=307398/).
For a Microsoft Visual C# .NET version of this article, see 304430 (/Feedback.aspx?kbNumber=304430/).
For a Microsoft Visual Basic .NET version of this article, see 304427 (/Feedback.aspx?kbNumber=304427/).

This article refers to the following Microsoft .NET Framework Class Library namespaces:

• System::ComponentModel
• System::Windows::Forms
• System::Drawing
INTRODUCTION

This step-by-step article describes how to do six basic file I/O operations in Microsoft Visual C++ 2005 or in Microsoft Visual C++ 2008. This article uses the Ecma C++/CLI syntax instead of the Managed Extensions for C++ syntax that Microsoft Knowledge Base article 307398 describes.

For more information, click the following article number to view the article in the Microsoft Knowledge Base:

307398 (/Feedback.aspx?kbNumber=307398/) How to do basic file I/O in Visual C++ 2005 or in Visual C++ .NET
On This Page

The object model for file operations in the Microsoft .NET Framework resembles the FileSystemObject (FSO) that is popular with many Microsoft Visual Studio 6.0 developers. The functionality that this article describes is based on the following Microsoft Knowledge Base article:
186118 (/Feedback.aspx?kbNumber=186118/) How to use FileSystemObject with Visual Basic

You can still use the FSO in the .NET Framework. Because the FSO is a COM component, the .NET Framework requires that access to the object be through the Interop layer. The .NET Framework generates a wrapper for the component for you if you want to use the component. However, the File class, the FileInfo class, the Directory class, the DirectoryInfo class, and other related classes in the .NET Framework offer functionality that is not available through the FSO without the overhead of the Interop layer.

Back to the top

Requirements

The following list outlines the hardware, the software, the network infrastructure, and the service packs that are required:

• Visual C++ 2005 or Visual C++ 2008

Back to the top

Demonstrated file I/O operations

The examples in this article describe basic file I/O operations. The Step-by-step example section describes how to create a sample program that demonstrates the following six file I/O operations:

• Read a text file
• Write a text file
• View file information
• List disk drives
• List folders
• List files

Back to the top

Read a text file

The following sample code uses a StreamReader class to read a text file. The contents of the file are added to a ListBox control. The try…catch block is used to warn the program if the file is empty. There are many ways to determine when the end of the file is reached. This sample uses the Peek method to examine the next line before it reads the next line.

listBox1->Items->Clear();try {    String^ textFile = String::Concat(windir,  mytest.txt);    StreamReader^ reader = gcnew StreamReader(textFile);    do    {        listBox1->Items->Add(reader->ReadLine());    }    while(reader->Peek() != -1);}catch(FileNotFoundException^ ex){    listBox1->Items->Add(ex);}catch(System::Exception^ e){    listBox1->Items->Add(e);}

Back to the top

Write a text file

This sample code uses a StreamWriter class to create and to write to a file. If you have an existing file, you can open it in the same manner.

StreamWriter^ pwriter = gcnew StreamWriter(C:  KBTest.txt);pwriter->WriteLine(File created using StreamWriter class.);pwriter->Close();listBox1->Items->Clear();String ^filew = gcnew String(File Written to C:  KBTest.txt);listBox1->Items->Add(filew);

Back to the top

View file information

This sample code uses a FileInfo class to access a file’s properties. This sample uses Notepad. The properties appear in a ListBox control.

listBox1->Items->Clear();String^ testfile = String::Concat(windir,  notepad.exe);FileInfo^ pFileProps = gcnew FileInfo(testfile);listBox1->Items->Add(String::Concat(File Name = , pFileProps->FullName));listBox1->Items->Add(String::Concat(Creation Time = , pFileProps->CreationTime.ToString()));listBox1->Items->Add(String::Concat(Last Access Time = , pFileProps->LastAccessTime.ToString()));listBox1->Items->Add(String::Concat(Last Write Time = , pFileProps->LastWriteTime.ToString()));listBox1->Items->Add(String::Concat(Size = , pFileProps->Length.ToString()));

Back to the top

List disk drives

This sample code uses the Directory class and the Drive class to list the logical drives on a system. For this sample, the results appear in a ListBox control.

listBox1->Items->Clear();cli::array<String^>^ drives = Directory::GetLogicalDrives();int numDrives = drives->Length;for(int i=0; i<numDrives; i++){    listBox1->Items->Add(drives[i]);}

Back to the top

List subfolders

This sample code uses the GetDirectories method of the Directory class to obtain a list of folders.

listBox1->Items->Clear();cli::array<String^>^ dirs = Directory::GetDirectories(windir);int numDirs = dirs->Length;for(int i=0; i<numDirs; i++){    listBox1->Items->Add(dirs[i]);}

Back to the top

List files

This sample code uses the GetFiles method of the Directory class to obtain a list of files.

listBox1->Items->Clear();cli::array<String^>^ files = Directory::GetFiles(windir);int numFiles = files->Length;for(int i=0; i<numFiles; i++){    listBox1->Items->Add(files[i]);}

Many things can go wrong when a user gains access to files. The files may not exist, the files may be in use, or users may not have rights on the files in the folders that they are trying to access. Consider these possibilities when you write code to handle the exceptions that may be generated.

Back to the top

Step-by-step example

1. Start Microsoft Visual Studio 2005 or Microsoft Visual C++ 2008.
2. On the File menu, point to New, and then click Project.
3. Under Project Types, click Visual C++ Projects. Under Templates, click Windows Forms Application.

Note If your default programming language is not Visual C++, you may see Visual C++ Projects under Other Languages.

4. Type KB950617 in the Name box, type C: in the Location box, and then click OK.
5. Open the Form1 form in Design view, and then press F4 to open the Properties window.
6. In the Properties window, expand the Size property folder. In the Width box, type 700. In the Height box, type 320.
7. Add one ListBox control and six Button controls to Form1.

Note To view the toolbox, click Toolbox on the View menu.

8. In the Properties window, change the Location property, the Name property, the Size property, the TabIndex property, and the Text property of these controls as follows:
Control ID Location Name Size TabIndex Text
button1 500, 32 button1 112, 23 1 Read Text File
button2 500, 64 button2 112, 23 2 Write Text File
button3 500, 96 button3 112, 23 3 View File Information
button4 500, 128 button4 112, 23 4 List Drives
button5 500, 160 button5 112, 23 5 List Subfolders
button6 500, 192 button6 112, 23 6 List Files
listBox1 24, 24 listBox1 450, 200 0
9. Open the Form1.h file. In the Form1 class declaration, declare one private String variable by using the following code:
private: String^ windir; 

10. In the Form1 class constructor, add the following code:
windir = System::Environment::GetEnvironmentVariable(windir);

11. To perform file I/O operations, add the System::IO namespace.
12. In Solution Explorer, select Form1.h, and then click Designer in the View menu to open Form1 in Design view. Double-click the Read Text File button, and then paste the following code in the button click handler:
					// How to read a text file:					// Use try...catch to deal with a 0-byte file or a nonexistent file.					listBox1->Items->Clear();					try {						StreamReader^ reader = gcnew StreamReader(c:  mytest.txt);						do						{							listBox1->Items->Add(reader->ReadLine());						}						while(reader->Peek() != -1);					}					catch(FileNotFoundException^ ex)					{						listBox1->Items->Add(ex);					}					catch(System::Exception^ e)					{						listBox1->Items->Add(e);					}

13. In Design view in Form1, double-click the Write Text File button, and then paste the following code in the button click handler:
// This shows you how to create and to write to a text file.StreamWriter^ pwriter = gcnew StreamWriter(c:  KBTest.txt);pwriter->WriteLine(The file was created by using the StreamWriter class.);pwriter->Close();listBox1->Items->Clear();String^ filew = gcnew String(File written to c:  KBTest.txt);listBox1->Items->Add(filew);

14. In Design view in Form1, double-click the View File Information button, and then paste the following code in the method:
// This code retrieves file properties. The example uses Notepad.exe.listBox1->Items->Clear();String^ testfile = String::Concat(windir,  notepad.exe);FileInfo^ pFileProps = gcnew FileInfo(testfile);listBox1->Items->Add(String::Concat(File Name = , pFileProps->FullName));listBox1->Items->Add(String::Concat(Creation Time = , pFileProps->CreationTime.ToString()));listBox1->Items->Add(String::Concat(Last Access Time = , pFileProps->LastAccessTime.ToString()));listBox1->Items->Add(String::Concat(Last Write Time = , pFileProps->LastWriteTime.ToString()));listBox1->Items->Add(String::Concat(Size = , pFileProps->Length.ToString()));

15. In Design view in Form1, double-click the List Drives button, and then paste the following code:
// This shows you how to obtain a list of disk drivers.listBox1->Items->Clear();cli::array<String^>^ drives = Directory::GetLogicalDrives();int numDrives = drives->Length;for(int i=0; i<numDrives; i++){    listBox1->Items->Add(drives[i]);}

16. In Design view in Form1, double-click the List Subfolders button, and then paste the following code:
// This code obtains a list of folders. This example uses the Windows folder.listBox1->Items->Clear();cli::array<String^>^ dirs = Directory::GetDirectories(windir);int numDirs = dirs->Length;for(int i=0; i<numDirs; i++){    listBox1->Items->Add(dirs[i]);}

17. In Design view in Form1, double-click the List Files button, and then paste the following code:
// This code obtains a list of files. This example uses the Windows folder.listBox1->Items->Clear();cli::array<String^>^ files = Directory::GetFiles(windir);int numFiles = files->Length;for(int i=0; i<numFiles; i++){    listBox1->Items->Add(files[i]);}

18. To build and then to run the program, press CTRL+F5.

Back to the top

Complete code sample

// Form1.h#pragma oncenamespace KB950617    using namespace System;    using namespace System::ComponentModel;    using namespace System::Collections;    using namespace System::Windows::Forms;    using namespace System::Data;    using namespace System::Drawing;    using namespace System::IO;    public ref class Form1 : public System::Windows::Forms::Form    {    private:        String^ windir;    public:        Form1(void)        {            InitializeComponent();            windir = System::Environment::GetEnvironmentVariable(windir);        }    protected:        ~Form1()        {            if (components)            {                delete components;            }        }    private: System::Windows::Forms::ListBox^  listBox1;    private: System::Windows::Forms::Button^  button1;    private: System::Windows::Forms::Button^  button2;    private: System::Windows::Forms::Button^  button3;    private: System::Windows::Forms::Button^  button4;    private: System::Windows::Forms::Button^  button5;    private: System::Windows::Forms::Button^  button6;    private:        System::ComponentModel::Container ^components;#pragma region Windows Form Designer generated code        void InitializeComponent(void)        {            this->listBox1 = (gcnew System::Windows::Forms::ListBox());            this->button1 = (gcnew System::Windows::Forms::Button());            this->button2 = (gcnew System::Windows::Forms::Button());            this->button3 = (gcnew System::Windows::Forms::Button());            this->button4 = (gcnew System::Windows::Forms::Button());            this->button5 = (gcnew System::Windows::Forms::Button());            this->button6 = (gcnew System::Windows::Forms::Button());            this->SuspendLayout();            // listBox1            this->listBox1->FormattingEnabled = true;            this->listBox1->Location = System::Drawing::Point(24, 24);            this->listBox1->Name = LlistBox1;            this->listBox1->Size = System::Drawing::Size(450, 199);            this->listBox1->TabIndex = 0;            // button1            this->button1->Location = System::Drawing::Point(500, 32);            this->button1->Name = Lbutton1;            this->button1->Size = System::Drawing::Size(112, 23);            this->button1->TabIndex = 1;            this->button1->Text = LRead Text File;            this->button1->UseVisualStyleBackColor = true;            this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);            // button2            this->button2->Location = System::Drawing::Point(500, 64);            this->button2->Name = Lbutton2;            this->button2->Size = System::Drawing::Size(112, 23);            this->button2->TabIndex = 2;            this->button2->Text = LWrite Text File;            this->button2->UseVisualStyleBackColor = true;            this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click);            // button3            this->button3->Location = System::Drawing::Point(500, 96);            this->button3->Name = Lbutton3;            this->button3->Size = System::Drawing::Size(112, 23);            this->button3->TabIndex = 3;            this->button3->Text = LView File Information;            this->button3->UseVisualStyleBackColor = true;            this->button3->Click += gcnew System::EventHandler(this, &Form1::button3_Click);            // button4            this->button4->Location = System::Drawing::Point(500, 128);            this->button4->Name = Lbutton4;            this->button4->Size = System::Drawing::Size(112, 23);            this->button4->TabIndex = 4;            this->button4->Text = LList Drives;            this->button4->UseVisualStyleBackColor = true;            this->button4->Click += gcnew System::EventHandler(this, &Form1::button4_Click);            // button5            this->button5->Location = System::Drawing::Point(500, 160);            this->button5->Name = Lbutton5;            this->button5->Size = System::Drawing::Size(112, 23);            this->button5->TabIndex = 5;            this->button5->Text = LList Subfolders;            this->button5->UseVisualStyleBackColor = true;            this->button5->Click += gcnew System::EventHandler(this, &Form1::button5_Click);            // button6            this->button6->Location = System::Drawing::Point(500, 192);            this->button6->Name = Lbutton6;            this->button6->Size = System::Drawing::Size(112, 23);            this->button6->TabIndex = 6;            this->button6->Text = LList Files;            this->button6->UseVisualStyleBackColor = true;            this->button6->Click += gcnew System::EventHandler(this, &Form1::button6_Click);            // Form1            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;            this->ClientSize = System::Drawing::Size(692, 286);            this->Controls->Add(this->button6);            this->Controls->Add(this->button5);            this->Controls->Add(this->button4);            this->Controls->Add(this->button3);            this->Controls->Add(this->button2);            this->Controls->Add(this->button1);            this->Controls->Add(this->listBox1);            this->Name = LForm1;            this->Text = LForm1;            this->ResumeLayout(false);        }#pragma endregion    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {                 					// How to read a text file:					// Use try...catch to deal with a 0-byte file or a non-existent file.					listBox1->Items->Clear();					try {						StreamReader^ reader = gcnew StreamReader(c:  mytest.txt);						do						{							listBox1->Items->Add(reader->ReadLine());						}						while(reader->Peek() != -1);					}					catch(FileNotFoundException^ ex)					{						listBox1->Items->Add(ex);					}					catch(System::Exception^ e)					{						listBox1->Items->Add(e);					}             }    private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) {                 // This demonstrates how to create and to write to a text file.                 StreamWriter^ pwriter = gcnew StreamWriter(c:  KBTest.txt);                 pwriter->WriteLine(The file was created by using the StreamWriter class.);                 pwriter->Close();                 listBox1->Items->Clear();                 String^ filew = gcnew String(File written to c:  KBTest.txt);                 listBox1->Items->Add(filew);             }    private: System::Void button3_Click(System::Object^  sender, System::EventArgs^  e) {                 // This code retrieves file properties. The example uses Notepad.exe.                 listBox1->Items->Clear();                 String^ testfile = String::Concat(windir,  notepad.exe);                 FileInfo^ pFileProps = gcnew FileInfo(testfile);                 listBox1->Items->Add(String::Concat(File Name = , pFileProps->FullName));                 listBox1->Items->Add(String::Concat(Creation Time = , pFileProps->CreationTime.ToString()));                 listBox1->Items->Add(String::Concat(Last Access Time = , pFileProps->LastAccessTime.ToString()));                 listBox1->Items->Add(String::Concat(Last Write Time = , pFileProps->LastWriteTime.ToString()));                 listBox1->Items->Add(String::Concat(Size = , pFileProps->Length.ToString()));             }    private: System::Void button4_Click(System::Object^  sender, System::EventArgs^  e) {                 // This demonstrates how to obtain a list of disk drivers.                 listBox1->Items->Clear();                 cli::array<String^>^ drives = Directory::GetLogicalDrives();                 int numDrives = drives->Length;                 for(int i=0; i<numDrives; i++)                 {                     listBox1->Items->Add(drives[i]);                 }             }    private: System::Void button5_Click(System::Object^  sender, System::EventArgs^  e) {                 // This code obtains a list of folders. This example uses the Windows folder.                 listBox1->Items->Clear();                 cli::array<String^>^ dirs = Directory::GetDirectories(windir);                 int numDirs = dirs->Length;                 for(int i=0; i<numDirs; i++)                 {                     listBox1->Items->Add(dirs[i]);                 }             }    private: System::Void button6_Click(System::Object^  sender, System::EventArgs^  e) {                 // This code obtains a list of files. This example uses the Windows folder.                 listBox1->Items->Clear();                 cli::array<String^>^ files = Directory::GetFiles(windir);                 int numFiles = files->Length;                 for(int i=0; i<numFiles; i++)                 {                     listBox1->Items->Add(files[i]);                 }             }    };}// KB950617.cpp#include stdafx.h#include Form1.husing namespace KB950617;[STAThreadAttribute]int main(array<System::String ^> ^args){    // Enable Windows XP visual effects before any controls are created.    Application::EnableVisualStyles();    Application::SetCompatibleTextRenderingDefault(false);     // Create the main window and run the program.    Application::Run(gcnew Form1());    return 0;}

Back to the top

REFERENCES

For more information, visit the following Microsoft Web site:
http://support.microsoft.com/default.aspx?xmlid=fh;EN-US;vcnet (http://support.microsoft.com/default.aspx?xmlid=fh;en-us;vcnet)

For more information about Visual C++ .NET, visit the following Microsoft Usenet newsgroup:

Microsoft.public.dotnet.languages.vc (http://msdn.microsoft.com/newsgroups/default.aspx?query=Microsoft.public.dotnet.languages.vc+&dg=&cat=en-us-msdn&lang=en&cr=US&pt=&catlist=774F24A2-F71F-425F-AC2B-DC48AB0DA5C9&dglist=&ptlist=&exp=&sloc=en-us)

For more information about how to create Windows forms in Managed Extensions for C++, see the ManagedCWinFormWiz sample in Visual Studio .NET Help.

For more information about ECMA C++/CLI, visit the following Microsoft Developer Network (MSDN) Web site:

http://msdn2.microsoft.com/en-us/library/ms379617.aspx (http://msdn2.microsoft.com/en-us/library/ms379617.aspx)

Back to the top



APPLIES TO
• Microsoft Visual C++ 2008 Express Edition
• Microsoft Visual C++ 2005 Express Edition

Back to the top

Keywords: 
kbwindowsforms kbio kbforms kbnewsgrouplink kbfileio kbinfo KB950617

Back to the top

 

Microsoft Knowledge Base Article

This article contents is Microsoft Copyrighted material.
Microsoft Corporation. All rights reserved. Terms of Use | Trademarks


You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

AddThis Social Bookmark Button

Leave a Reply

*
To prove that you're not a bot, enter this code
Anti-Spam Image