Notice: This website is an unofficial Microsoft Knowledge Base (hereinafter KB) archive and is intended to provide a reliable access to deleted content from Microsoft KB. All KB articles are owned by Microsoft Corporation. Read full disclaimer for more details.

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


For a Managed Extensions for C++ version of this article, see 307398 .

For a Microsoft Visual C# .NET version of this article, see 304430 .

For a Microsoft Visual Basic .NET version of this article, see 304427 .

This article refers to the following Microsoft .NET Framework Class Library namespaces:
  • System::ComponentModel
  • System::Windows::Forms
  • System::Drawing

↑ Back to the top


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 How to do basic file I/O in Visual C++ 2005 or in Visual C++ .NET

↑ Back to the top


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 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.

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

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

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);
}

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);

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()));

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]);
}

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]);
}

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.

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 IDLocationNameSizeTabIndexText
    button1500, 32button1112, 231Read Text File
    button2500, 64button2112, 232Write Text File
    button3500, 96button3112, 233View File Information
    button4500, 128button4112, 234List Drives
    button5500, 160button5112, 235List Subfolders
    button6500, 192button6112, 236List Files
    listBox124, 24listBox1450, 2000
  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::IOnamespace.
  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.

Complete code sample

// Form1.h
#pragma once

namespace 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 = L"listBox1";
this->listBox1->Size = System::Drawing::Size(450, 199);
this->listBox1->TabIndex = 0;
// button1
this->button1->Location = System::Drawing::Point(500, 32);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(112, 23);
this->button1->TabIndex = 1;
this->button1->Text = L"Read 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 = L"button2";
this->button2->Size = System::Drawing::Size(112, 23);
this->button2->TabIndex = 2;
this->button2->Text = L"Write 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 = L"button3";
this->button3->Size = System::Drawing::Size(112, 23);
this->button3->TabIndex = 3;
this->button3->Text = L"View 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 = L"button4";
this->button4->Size = System::Drawing::Size(112, 23);
this->button4->TabIndex = 4;
this->button4->Text = L"List 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 = L"button5";
this->button5->Size = System::Drawing::Size(112, 23);
this->button5->TabIndex = 5;
this->button5->Text = L"List 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 = L"button6";
this->button6->Size = System::Drawing::Size(112, 23);
this->button6->TabIndex = 6;
this->button6->Text = L"List 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 = L"Form1";
this->Text = L"Form1";
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.h"

using 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: 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:

↑ Back to the top


Keywords: kbwindowsforms, kbio, kbforms, kbnewsgrouplink, kbentirenet, kbdsupport, kbfileio, kbinfo, kb

↑ Back to the top

Article Info
Article ID : 950617
Revision : 1
Created on : 1/7/2017
Published on : 10/26/2012
Exists online : False
Views : 141