Fazer E/S de arquivo básico no Visual C++

Este artigo descreve como fazer operações básicas de entrada/saída de arquivo (E/S) no Microsoft Visual C++ ou no Visual C++ .NET.

Versão original do produto: Visual C++
Número de KB original: 307398

Resumo

Se você for novo no .NET Framework, descobrirá que o modelo de objeto para operações de arquivo no .NET Framework é semelhante ao que é popular entre muitos desenvolvedores do FileSystemObject Visual Studio.

Este artigo refere-se aos seguintes namespaces da Biblioteca de Classes .NET Framework:

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

Você ainda pode usar o FileSystemObject no .NET Framework. Como o FileSystemObject é um componente COM (Component Object Model), o .NET Framework exige que o acesso ao objeto seja por meio da camada Interop. O .NET Framework gera um wrapper para o componente para você se você quiser usá-lo. No entanto, a File classe, a FileInfo classe, as Directoryclasses , DirectoryInfo e outras classes relacionadas no .NET Framework, oferecem funcionalidade que não está disponível com o FileSystemObject, sem a sobrecarga da camada Interop.

Operações de E/S de arquivo demonstradas

Os exemplos neste artigo descrevem operações básicas de E/S de arquivo. A seção Exemplo passo a passo descreve como criar um programa de exemplo que demonstre as seis operações de E/S de arquivo a seguir:

Ler um arquivo de texto

O código de exemplo a seguir usa uma StreamReader classe para ler um arquivo de texto. O conteúdo do arquivo é adicionado a um controle ListBox. O try...catch bloco é usado para alertar o programa se o arquivo estiver vazio. Há muitas maneiras de determinar quando o final do arquivo é atingido; este exemplo usa o Peek método para examinar a próxima linha antes de lê-la.

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

No Visual C++, você deve adicionar a opção do compilador de suporte de runtime de linguagem comum (/clr:oldSyntax) para compilar com êxito o exemplo de código anterior como C++gerenciado. Para adicionar a opção do compilador de suporte do common language runtime, siga estas etapas:

  1. Clique em Projeto e clique <em Propriedades do ProjectName>.

    Observação

    <ProjectName> é um espaço reservado para o nome do projeto.

  2. Expanda Propriedades de Configuração e clique em Geral.

  3. No painel direito, clique para selecionar Suporte ao Common Language Runtime, Sintaxe Antiga (/clr:oldSyntax) nas configurações de projeto de suporte do Common Language Runtime.

  4. Na caixa Plano de discagem (Contexto de telefone), clique em Procurar para localizar o plano de discagem do usuário.

Gravar um arquivo de texto

Este código de exemplo usa uma StreamWriter classe para criar e gravar em um arquivo. Se você tiver um arquivo existente, poderá abri-lo da mesma maneira.

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

Exibir informações de arquivo

Este código de exemplo usa uma FileInfo classe para acessar as propriedades de um arquivo. Notepad.exe é usado neste exemplo. As propriedades aparecem em um controle 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()));

Listar unidades de disco

Este código de exemplo usa as Directory classes e Drive para listar as unidades lógicas em um sistema. Para este exemplo, os resultados aparecem em um controle 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]);
}

Listar subpastas

Este código de exemplo usa o GetDirectories método da Directory classe para obter uma lista de pastas.

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

Listar arquivos

Este código de exemplo usa o GetFiles método da Directory classe para obter uma listagem de arquivos.

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

Muitas coisas podem dar errado quando um usuário obtém acesso aos arquivos. Os arquivos podem não existir, os arquivos podem estar em uso ou os usuários podem não ter direitos nos arquivos de pastas que estão tentando acessar. Considere essas possibilidades ao gravar código para lidar com as exceções que podem ser geradas.

Exemplo passo a passo

  1. Inicie o Visual Studio .NET.

  2. No menu arquivo, aponte para novo e, em seguida, clique em Project.

  3. Em Tipos de Projeto, clique em Projetos do Visual C++. Na seção Modelos, clique em Windows Forms Aplicativo (.NET).

  4. Digite KB307398 na caixa Nome , digite C:\ na caixa Localização e clique em OK.

  5. Abra o formulário Form1 na exibição Design e pressione F4 para abrir a janela Propriedades .

  6. Na janela Propriedades , expanda a pasta Tamanho . Na caixa Largura , digite 700. Na caixa Altura , digite 320.

  7. Adicione um controle ListBox e seis controles button ao Form1.

    Observação

    Para exibir a caixa de ferramentas, clique em Caixa de Ferramentas no menu Exibir .

  8. Na janela Propriedades , altere o Local, o Nome, o Tamanho, o TabIndex e as propriedades Texto desses controles da seguinte maneira:

    ID de Controle Localização Nome Tamanho TabIndex Texto
    button1 500, 32 button1 112, 23 1 Ler arquivo de texto
    button2 500, 64 button2 112, 23 2 Gravar arquivo de texto
    button3 500, 96 button3 112, 23 3 Exibir informações de arquivo
    button4 500, 128 button4 112, 23 4 Listar unidades
    button5 500, 160 button5 112, 23 5 Listar subpastas
    button6 500, 192 button6 112, 23 6 Listar arquivos
    listBox1 24, 24 listBox1 450, 200 0 listBox1
  9. Abra o arquivo Form1.h . Na declaração de Form1 classe, declare uma variável privada String com o seguinte código:

    private:
    String *windir;
    
  10. No construtor de Form1 classe, adicione o seguinte código:

    windir = System::Environment::GetEnvironmentVariable("windir");
    
  11. Para fazer operações de saída de entrada de arquivo, adicione o System::IO namespace.

  12. Pressione SHIFT+F7 para abrir o Formulário1 na exibição Design. Clique duas vezes no botão Ler Arquivo de Texto e cole o seguinte código:

    // 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. Na exibição Design do Form1, clique duas vezes no botão Gravar Arquivo de Texto e cole o seguinte código:

    // 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. Na exibição Design do Form1, clique duas vezes no botão Exibir Informações do Arquivo e cole o seguinte código no método:

    // 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. Na exibição Design do Form1, clique duas vezes no botão Unidades de Lista e cole o seguinte código:

    // 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. Na exibição Design do Form1, clique duas vezes no botão Listar Subpastas e cole o seguinte código:

    // 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. Na exibição Design do Form1, clique duas vezes no botão Arquivos de Lista e cole o seguinte código:

    // 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. Para criar e executar o programa, pressione CTRL+F5.

Exemplo de código completo

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

Referências

Para obter mais informações, visite Suporte da Microsoft. Para obter mais informações sobre como criar formulários do Windows em extensões gerenciadas para C++, confira o ManagedCWinFormWiz exemplo no Visual Studio .NET Help.