Выполнение базовых операций ввода-вывода файлов в Visual C++
В этой статье описывается, как выполнять базовые операции ввода-вывода файлов в Microsoft Visual C++ или Visual C++ .NET.
Исходная версия продукта: Visual C++
Исходный номер базы знаний: 307398
Итоги
Если вы не знакомы с платформа .NET Framework, вы найдете, что объектная модель для операций с файлами в платформа .NET Framework похожа на FileSystemObject
популярную для многих разработчиков Visual Studio.
Чтобы упростить переход, см. статью "Использование FileSystemObject" с Visual Basic.
Сведения о версии Visual C# .NET этой статьи см. в статье "Как выполнять базовый ввод-вывод файлов в Visual C#".
В этой статье приведены следующие пространства имен библиотеки классов платформа .NET Framework:
System::ComponentModel
System::Windows::Forms
System::Drawing
Вы по-прежнему можете использовать FileSystemObject
его в платформа .NET Framework. FileSystemObject
Поскольку компонент является компонентом com-модели компонента, платформа .NET Framework требует доступа к объекту через слой взаимодействия. Платформа .NET Framework создает оболочку для компонента, если вы хотите его использовать. File
Однако класс, класс, класс, DirectoryInfo
FileInfo
Directory
классы и другие связанные классы в платформа .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, выполните следующие действия.
Щелкните "Проект" и выберите <"Свойства ProjectName>".
Примечание.
<> Имя проекта — это заполнитель для имени проекта.
Разверните свойства конфигурации и нажмите кнопку "Общие".
В правой области щелкните, чтобы выбрать поддержку среды clr (/clr:oldSyntax) в параметрах проекта поддержки среды CLR.
Щелкните Применить, затем щелкните ОК.
Написание текстового файла
Этот пример кода использует 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()));
Вывод списка дисков
Этот пример кода использует Directory
и Drive
классы для перечисления логических дисков в системе. В этом примере результаты отображаются в элементе управления 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]);
}
Многие вещи могут пойти не так, когда пользователь получает доступ к файлам. Файлы могут не существовать, файлы могут использоваться или пользователи могут не иметь прав на файлы папок, к которым они пытаются получить доступ. Учитывайте эти возможности при написании кода для обработки исключений, которые могут быть созданы.
Пошаговый пример
Запустите Visual Studio .NET.
В меню Файл выберите пункт Создать и затем пункт Проект.
В разделе "Типы проектов" щелкните "Проекты Visual C++". В разделе "Шаблоны" щелкните приложение Windows Forms (.NET).
Введите KB307398 в поле "Имя", введите
C:\
в поле "Расположение" и нажмите кнопку "ОК".Откройте форму Form1 в представлении конструктора и нажмите клавишу F4, чтобы открыть окно "Свойства".
В окне "Свойства" разверните папку "Размер". В поле "Ширина" введите 700. В поле "Высота" введите 320.
Добавьте один элемент управления ListBox и шесть элементов управления Button в Form1.
Примечание.
Чтобы просмотреть панель элементов, щелкните панель элементов в меню "Вид ".
В окне "Свойства" измените расположение, имя, размер, tabIndex и свойства text этих элементов управления следующим образом:
Идентификатор элемента управления Расположение Имя. Размер 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 Откройте файл Form1.h. В объявлении класса объявите
Form1
одну частнуюString
переменную со следующим кодом:private: String *windir;
В конструкторе
Form1
классов добавьте следующий код:windir = System::Environment::GetEnvironmentVariable("windir");
Чтобы выполнить операции вывода входных данных файла, добавьте
System::IO
пространство имен.Нажмите клавиши 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); }
В представлении конструктора 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);
В представлении конструктора 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()));
В представлении конструктора 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]); }
В представлении конструктора 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]); }
В представлении конструктора 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]); }
Чтобы создать и запустить программу, нажмите клавиши 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 в управляемых расширениях для C++см ManagedCWinFormWiz
. в примере справки Visual Studio .NET.