Visual C++ で基本的なファイル I/O を実行する

この記事では、Microsoft Visual C++または Visual C++ .NET で基本的なファイル入出力 (I/O) 操作を実行する方法について説明します。

元の製品バージョン: Visual C++
元の KB 番号: 307398

概要

.NET Frameworkを初めて使用する場合、.NET Frameworkでのファイル操作のオブジェクト モデルは、多くの Visual Studio 開発者に人気のある オブジェクト モデルと似ていますFileSystemObject

この記事では、次の.NET Framework クラス ライブラリ名前空間について説明します。

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

.NET Frameworkでは 引き続き をFileSystemObject使用できます。 FileSystemObjectはコンポーネント オブジェクト モデル (COM) コンポーネントであるため、.NET Frameworkは相互運用機能レイヤーを介してオブジェクトにアクセスする必要があります。 .NET Frameworkを使用する場合は、コンポーネントのラッパーが生成されます。 ただし、.NET Framework内のFileFileInfoクラス、クラス、Directory、クラスDirectoryInfo、およびその他の関連クラスは、相互運用機能レイヤーのオーバーヘッドなしで、 ではFileSystemObject使用できない機能を提供します。

デモンストレーションされたファイル I/O 操作

この記事の例では、基本的なファイル I/O 操作について説明します。 「 ステップ バイ ステップの例 」セクションでは、次の 6 つのファイル I/O 操作を示すサンプル プログラムを作成する方法について説明します。

テキスト ファイルの読み取り

次のサンプル コードでは、 クラスを StreamReader 使用してテキスト ファイルを読み取ります。 ファイルの内容が ListBox コントロールに追加されます。 ブロックは try...catch 、ファイルが空の場合にプログラムに警告するために使用されます。 ファイルの末尾に到達するタイミングを判断する方法は多数あります。このサンプルでは、 メソッドを Peek 使用して、読み取る前に次の行を調べます。

listBox1->Items->Clear();
try
{
    String* textFile = String::Concat(windir, (S"\\mytest.txt"));
    StreamReader *reader=new  StreamReader(textFile);
    do
    {
        listBox1->Items->Add(reader->ReadLine());
    } while(reader->Peek() != -1);
}

catch (System::Exception *e)
{
    listBox1->Items->Add(e);
}

Visual C++ では、前のコード サンプルをマネージド C++ として正常にコンパイルするには、共通言語ランタイム サポート コンパイラ オプション (/clr:oldSyntax) を追加する必要があります。 共通言語ランタイム サポート コンパイラ オプションを追加するには、次の手順に従います。

  1. [プロジェクト] をクリックし、[ProjectName> プロパティ] をクリックします<

    注:

    <ProjectName> は、プロジェクトの名前のプレースホルダーです。

  2. [ 構成プロパティ] を展開し、[ 全般] をクリックします。

  3. 右側のウィンドウで、共通言語ランタイム サポート プロジェクトの設定で[ 共通言語ランタイム サポート]、[古い構文 (/clr:oldSyntax)] をクリックして選択します。

  4. [ダイヤル プラン (電話のコンテキスト)] ボックスで、[参照] をクリックして、ユーザーのダイヤル プランを見つけます。

テキスト ファイルを書き込む

このサンプル コードでは、 クラスを StreamWriter 使用して、ファイルの作成と書き込みを行います。 既存のファイルがある場合は、同じ方法で開くことができます。

StreamWriter* pwriter = new StreamWriter(S"c:\\KBTest.txt");
pwriter->WriteLine(S"File created using StreamWriter class.");
pwriter->Close();
listBox1->Items->Clear();
String *filew = new String(S"File Written to C:\\KBTest.txt");
listBox1->Items->Add(filew);

ファイル情報を表示する

このサンプル コードでは、 クラスを FileInfo 使用してファイルのプロパティにアクセスします。 このサンプルでは、Notepad.exe を使用します。 プロパティは ListBox コントロールに表示されます。

listBox1->Items->Clear();
String* testfile = String::Concat(windir, (S"\\notepad.exe"));
FileInfo *pFileProps =new FileInfo(testfile);

listBox1->Items->Add(String::Concat(S"File Name = ", (pFileProps->get_FullName())));
listBox1->Items->Add(String::Concat(S"Creation Time = ", (pFileProps->get_CreationTime()).ToString()));
listBox1->Items->Add(String::Concat(S"Last Access Time = " ,(pFileProps->get_LastAccessTime()).ToString()));
listBox1->Items->Add(String::Concat(S"Last Write Time = ", (pFileProps->get_LastWriteTime()).ToString()));
listBox1->Items->Add(String::Concat(S"Size = ", (pFileProps->get_Length()).ToString()));

ディスク ドライブを一覧表示する

このサンプル コードでは、 クラスと Drive クラスをDirectory使用して、システム上の論理ドライブを一覧表示します。 このサンプルでは、結果は ListBox コントロールに表示されます。

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

サブ フォルダーを一覧表示する

このサンプル コードでは、 GetDirectories クラスの メソッドを Directory 使用してフォルダーの一覧を取得します。

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

ファイルの一覧表示

このサンプル コードでは、 GetFiles クラスの メソッドを Directory 使用して、ファイルの一覧を取得します。

listBox1->Items->Clear();
String* files[]= Directory::GetFiles(this->windir);
int numFiles = files->get_Length();
for (int i=0; i<numFiles; i++)
{
    listBox1->Items->Add(files[i]);
}

ユーザーがファイルにアクセスすると、多くの問題が発生する可能性があります。 ファイルが存在しないか、ファイルが使用中であるか、ユーザーがアクセスしようとしているフォルダーのファイルに対する権限がない可能性があります。 生成される可能性のある例外を処理するコードを記述するときは、これらの可能性を考慮してください。

ステップ バイ ステップの例

  1. Visual Studio .NET を起動します。

  2. [ ファイル] メニューの [ 新規] をポイントし、[ プロジェクト] をクリックします。

  3. [ プロジェクトの種類] で、[ Visual C++ プロジェクト] をクリックします。 [テンプレート] セクションで、[アプリケーション (.NET) Windows フォームクリックします。

  4. [名前] ボックスに「KB307398」と入力し、[場所] ボックスに「」と入力C:\し、[OK] をクリックします

  5. デザイン ビューで Form1 フォームを開き、F4 キーを押して [プロパティ ] ウィンドウを開きます。

  6. [ プロパティ ] ウィンドウで、[ サイズ ] フォルダーを展開します。 [ ] ボックスに「 700」と入力します。 [ 高さ ] ボックスに「 320」と入力します。

  7. 1 つの ListBox コントロールと 6 つのボタン コントロールを Form1 に追加します。

    注:

    ツールボックスを表示するには、[表示] メニューの [ツールボックス] をクリックします。

  8. [ プロパティ ] ウィンドウで、次のように、これらのコントロールの LocationNameSizeTabIndexText プロパティを変更します。

    コントロール ID 場所 名前 Size TabIndex テキスト
    button1 500, 32 button1 112, 23 1 テキスト ファイルの読み取り
    button2 500, 64 button2 112, 23 2 テキスト ファイルの書き込み
    button3 500, 96 button3 112, 23 3 ファイル情報の表示
    button4 500, 128 button4 112, 23 4 ドライブを一覧表示する
    button5 500, 160 button5 112, 23 5 サブフォルダーの一覧表示
    button6 500, 192 button6 112, 23 6 ファイルの一覧表示
    listBox1 24, 24 listBox1 450, 200 0 listBox1
  9. Form1.h ファイルを開きます。 クラス宣言で、次の Form1 コードを使用して 1 つのプライベート String 変数を宣言します。

    private:
    String *windir;
    
  10. クラス コンストラクターで Form1 、次のコードを追加します。

    windir = System::Environment::GetEnvironmentVariable("windir");
    
  11. ファイル入力出力操作を実行するには、名前空間を追加します System::IO

  12. Shift キーを押しながら F7 キーを押して、デザイン ビューで Form1 を開きます。 [ テキスト ファイルの読み取り ] ボタンをダブルクリックし、次のコードを貼り付けます。

    // How to read a text file:
    // Use try...catch to deal with a 0 byte file or a non-existant file.
    listBox1->Items->Clear();
    
    try
    {
        String* textFile = String::Concat(windir, (S"\\mytest.txt"));
        StreamReader *reader=new  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);
    }
    
  13. Form1 デザイン ビューで、[ テキスト ファイルの書き込み ] ボタンをダブルクリックし、次のコードを貼り付けます。

    // This demonstrates how to create and to write to a text file.
    StreamWriter* pwriter = new StreamWriter(S"c:\\KBTest.txt");
    pwriter->WriteLine(S"The file was created by using the StreamWriter class.");
    pwriter->Close();
    listBox1->Items->Clear();
    String *filew = new String(S"File written to C:\\KBTest.txt");
    listBox1->Items->Add(filew);
    
  14. Form1 デザイン ビューで、[ ファイル情報の表示 ] ボタンをダブルクリックし、メソッドに次のコードを貼り付けます。

    // This code retrieves file properties. The example uses Notepad.exe.
    listBox1->Items->Clear();
    String* testfile = String::Concat(windir, (S"\\notepad.exe"));
    FileInfo *pFileProps =new FileInfo(testfile);
    
    listBox1->Items->Add(String::Concat(S"File Name = ", (pFileProps->get_FullName())));
    listBox1->Items->Add(String::Concat(S"Creation Time = ", (pFileProps->get_CreationTime()).ToString()));
    listBox1->Items->Add(String::Concat(S"Last Access Time = " ,(pFileProps->get_LastAccessTime()).ToString()));
    listBox1->Items->Add(String::Concat(S"Last Write Time = ", (pFileProps->get_LastWriteTime()).ToString()));
    listBox1->Items->Add(String::Concat(S"Size = ", (pFileProps->get_Length()).ToString()));
    
  15. Form1 デザイン ビューで、[ドライブの一覧表示] ボタンをダブルクリックし、次のコードを貼り付けます。

    // This demonstrates how to obtain a list of disk drives.
    listBox1->Items->Clear();
    String* drives[] = Directory::GetLogicalDrives();
    int numDrives = drives->get_Length();
    for (int i=0; i<numDrives; i++)
    {
        listBox1->Items->Add(drives[i]);
    }
    
  16. Form1 デザイン ビューで、[サブフォルダーの一覧表示] ボタンをダブルクリックし、次のコードを貼り付けます。

    // This code obtains a list of folders. This example uses the Windows folder.
    listBox1->Items->Clear();
    String* dirs[] = Directory::GetDirectories(windir);
    int numDirs = dirs->get_Length();
    for (int i=0; i<numDirs; i++)
    {
        listBox1->Items->Add(dirs[i]);
    }
    
  17. Form1 デザイン ビューで、[ファイルの一覧表示] ボタンをダブルクリックし、次のコードを貼り付けます。

    // This code obtains a list of files. This example uses the Windows folder.
    listBox1->Items->Clear();
    String* files[]= Directory::GetFiles(this->windir);
    int numFiles = files->get_Length();
    for (int i=0; i<numFiles; i++)
    {
        listBox1->Items->Add(files[i]);
    }
    
  18. ビルドしてからプログラムを実行するには、Ctrl キーを押しながら F5 キーを押します。

完全なコード サンプル

//Form1.h
#pragma once

namespace KB307398
{
    using namespace System;
    using namespace System::IO;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;

    /// <summary>
    /// Summary for Form1
    /// WARNING: If you change the name of this class, you will need to change the
    ///          'Resource File Name' property for the managed resource compiler tool
    ///          associated with all .resx files this class depends on.  Otherwise,
    ///          the designers will not be able to interact properly with localized
    ///          resources associated with this form.
    /// </summary>
    public __gc class Form1 : public System::Windows::Forms::Form
    {
        private:
        String *windir;
        public:
        Form1(void)
        {
            windir = System::Environment::GetEnvironmentVariable("windir");
            InitializeComponent();
        }

        protected:
        void Dispose(Boolean disposing)
        {
            if (disposing && components)
            {
            components->Dispose();
            }
            __super::Dispose(disposing);
        }
        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::Windows::Forms::ListBox *  listBox1;

        private:
        /// <summary>
        /// Required designer variable.
        /// </summary>
        System::ComponentModel::Container * components;

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        void InitializeComponent(void)
        {
            this->button1 = new System::Windows::Forms::Button();
            this->button2 = new System::Windows::Forms::Button();
            this->button3 = new System::Windows::Forms::Button();
            this->button4 = new System::Windows::Forms::Button();
            this->button5 = new System::Windows::Forms::Button();
            this->button6 = new System::Windows::Forms::Button();
            this->listBox1 = new System::Windows::Forms::ListBox();
            this->SuspendLayout();
            // button1
            this->button1->Location = System::Drawing::Point(500, 32);
            this->button1->Name = S"button1";
            this->button1->Size = System::Drawing::Size(112, 23);
            this->button1->TabIndex = 1;
            this->button1->Text = S"Read Text File";
            this->button1->Click += new System::EventHandler(this, button1_Click);
            // button2
            this->button2->Location = System::Drawing::Point(500, 64);
            this->button2->Name = S"button2";
            this->button2->Size = System::Drawing::Size(112, 23);
            this->button2->TabIndex = 2;
            this->button2->Text = S"Write Text File";
            this->button2->Click += new System::EventHandler(this, button2_Click);
            // button3
            this->button3->Location = System::Drawing::Point(500, 96);
            this->button3->Name = S"button3";
            this->button3->Size = System::Drawing::Size(112, 23);
            this->button3->TabIndex = 3;
            this->button3->Text = S"View File Information";
            this->button3->Click += new System::EventHandler(this, button3_Click);
            // button4
            this->button4->Location = System::Drawing::Point(500, 128);
            this->button4->Name = S"button4";
            this->button4->Size = System::Drawing::Size(112, 23);
            this->button4->TabIndex = 4;
            this->button4->Text = S"List Drives";
            this->button4->Click += new System::EventHandler(this, button4_Click);
            // button5
            this->button5->Location = System::Drawing::Point(500, 160);
            this->button5->Name = S"button5";
            this->button5->Size = System::Drawing::Size(112, 23);
            this->button5->TabIndex = 5;
            this->button5->Text = S"List Subfolders";
            this->button5->Click += new System::EventHandler(this, button5_Click);
            // button6
            this->button6->Location = System::Drawing::Point(500, 188);
            this->button6->Name = S"button6";
            this->button6->Size = System::Drawing::Size(112, 23);
            this->button6->TabIndex = 6;
            this->button6->Text = S"List Files";
            this->button6->Click += new System::EventHandler(this, button6_Click);
            // listBox1
            this->listBox1->Location = System::Drawing::Point(24, 24);
            this->listBox1->Name = S"listBox1";
            this->listBox1->Size = System::Drawing::Size(450, 199);
            this->listBox1->TabIndex = 0;
            // Form1
            this->AutoScaleBaseSize = System::Drawing::Size(5, 13);
            this->ClientSize = System::Drawing::Size(692, 293);
            this->Controls->Add(this->listBox1);
            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->Name = S"Form1";
            this->Text = S"Form1";
            this->ResumeLayout(false);
        }
        private: System::Void button1_Click(System::Object *  sender, System::EventArgs *  e)
        {
            // This code shows how to read a text file.
            // The try...catch code is to deal with a 0 byte file or a non-existant file.
            listBox1->Items->Clear();

            try
            {
                String* textFile = String::Concat(windir, (S"\\mytest.txt"));
                StreamReader *reader=new  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);
            }
        }

        private: System::Void button2_Click(System::Object *  sender, System::EventArgs *  e)
        {
            // This code demonstrates how to create and to write to a text file.
            StreamWriter* pwriter = new StreamWriter(S"c:\\KBTest.txt");
            pwriter->WriteLine(S"The file was created by using the StreamWriter class.");
            pwriter->Close();
            listBox1->Items->Clear();
            String *filew = new String(S"The file was 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. This example uses Notepad.exe.
            listBox1->Items->Clear();
            String* testfile = String::Concat(windir, (S"\\notepad.exe"));
            FileInfo *pFileProps  =new FileInfo(testfile);

            listBox1->Items->Add(String::Concat(S"File Name = ", (pFileProps->get_FullName() )) );
            listBox1->Items->Add(String::Concat(S"Creation Time = ", (pFileProps->get_CreationTime() ).ToString()) );
            listBox1->Items->Add(String::Concat(S"Last Access Time = "  ,(pFileProps->get_LastAccessTime() ).ToString()) );
            listBox1->Items->Add(String::Concat(S"Last Write Time = ", (pFileProps->get_LastWriteTime() ).ToString()) );
            listBox1->Items->Add(String::Concat(S"Size = ", (pFileProps->get_Length() ).ToString()) );
        }

        private: System::Void button4_Click(System::Object *  sender, System::EventArgs *  e)
        {
            // The code demonstrates how to obtain a list of disk drives.
            listBox1->Items->Clear();
            String* drives[] = Directory::GetLogicalDrives();
            int numDrives = drives->get_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();
            String* dirs[] = Directory::GetDirectories(windir);
            int numDirs = dirs->get_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();
            String* files[]= Directory::GetFiles(this->windir);
            int numFiles = files->get_Length();
            for (int i=0; i<numFiles; i++)
            {
                listBox1->Items->Add(files[i]);
            }
        }
    };
}

//Form1.cpp
#include "stdafx.h"
#include "Form1.h"
#include <windows.h>

using namespace KB307398;

int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
    System::Threading::Thread::CurrentThread->ApartmentState = System::Threading::ApartmentState::STA;
    Application::Run(new Form1());
    return 0;
}

関連情報

詳細については、「Microsoft サポート」を参照してください。 C++ のマネージド拡張機能で Windows フォームを作成する方法の詳細については、Visual Studio .NET ヘルプの ManagedCWinFormWiz サンプルを参照してください。