Выполнение базового файлового ввода-вывода в Visual C++

В этой статье описывается выполнение основных операций ввода-вывода файлов в Microsoft Visual C++ или Visual C++ .NET.

Исходная версия продукта: Visual C++
Исходный номер базы знаний: 307398

Сводка

Если вы не знакомы с платформа .NET Framework, вы обнаружите, что объектная модель для операций с файлами в платформа .NET Framework похожа FileSystemObject на модель, которая пользуется популярностью у многих разработчиков Visual Studio.

В этой статье рассматриваются следующие платформа .NET Framework пространства имен библиотек классов:

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

Вы по-прежнему FileSystemObject можете использовать в платформа .NET Framework. FileSystemObject Так как является компонентом COM, платформа .NET Framework требует, чтобы доступ к объекту проходил через слой взаимодействия. Если вы хотите его использовать, платформа .NET Framework создает оболочку для компонента. File Однако класс, FileInfo класс , DirectoryDirectoryInfo классы и другие связанные классы в платформа .NET Framework предоставляют функциональные возможности, недоступные в FileSystemObject, без накладных расходов на уровень взаимодействия.

Демонстрация операций ввода-вывода файлов

В примерах в этой статье описываются основные операции ввода-вывода файлов. В разделе Пошаговый пример описывается создание примера программы, демонстрирующей следующие шесть операций ввода-вывода файлов:

Чтение текстового файла

В следующем примере кода класс используется 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++ необходимо добавить параметр компилятора поддержки среды CLR (/clr:oldSyntax), чтобы успешно скомпилировать предыдущий пример кода как управляемый C++. Чтобы добавить параметр компилятора поддержки среды CLR, выполните следующие действия.

  1. Щелкните Проект, а затем — <Свойства ProjectName>.

    Примечание.

    <ProjectName> — это заполнитель для имени проекта.

  2. Разверните узел Свойства конфигурации, а затем щелкните Общие.

  3. В правой области щелкните , чтобы выбрать Поддержка common Language Runtime, Old Syntax (/clr:oldSyntax) в параметрах проекта поддержки среды CLR.

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

Вывод списка файлов

В этом примере кода метод класса используется GetFilesDirectory для получения списка файлов.

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++. В разделе Шаблоны щелкните Windows Forms приложение (.NET).

  4. Введите KB307398 в поле Имя , введите C:\ в поле Расположение и нажмите кнопку ОК.

  5. Откройте форму Form1 в режиме конструктора и нажмите клавишу F4, чтобы открыть окно Свойства .

  6. В окне Свойства разверните папку Размер . В поле Ширина введите 700. В поле Высота введите 320.

  7. Добавьте один элемент управления ListBox и шесть элементов управления Button в Form1.

    Примечание.

    Чтобы просмотреть панель элементов, щелкните Панель элементов в меню Вид .

  8. В окне Свойства измените свойства Расположение, Имя, Размер, TabIndex и Текст этих элементов управления следующим образом:

    Идентификатор правила Расположение Имя Размер 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 Создание списка ресурсов Drive
    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 класса объявите одну частную 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;
}

Ссылки

Дополнительные сведения см. в разделе служба поддержки Майкрософт. Дополнительные сведения о создании Форм Windows Forms в управляемых расширениях для C++ см. в примере справки ManagedCWinFormWiz visual Studio .NET.