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 개체에 대한 액세스가 Interop 계층을 통해 있어야 합니다. .NET Framework 사용하려는 경우 구성 요소에 대한 래퍼를 생성합니다. 그러나 클래스, File 클래스, FileInfo 클래스DirectoryInfo, Directory클래스 및 .NET Framework 기타 관련 클래스는 Interop 계층의 오버헤드 없이 에서 사용할 수 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()));

디스크 드라이브 나열

이 샘플 코드는 DirectoryDrive 클래스를 사용하여 시스템의 논리 드라이브를 나열합니다. 이 샘플의 경우 결과는 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++ 프로젝트를 클릭합니다. 템플릿 섹션에서 Windows Forms 애플리케이션(.NET)을 클릭합니다.

  4. 이름 상자에 KB307398 입력하고 위치 상자를 입력 C:\ 한 다음 확인을 클릭합니다.

  5. 디자인 보기에서 Form1 양식을 연 다음 F4 키를 눌러 속성 창을 엽니다.

  6. 속성 창에서 크기 폴더를 확장합니다. 너비 상자에 700을 입력합니다. 높이 상자에 320을 입력합니다.

  7. Form1에 ListBox 컨트롤 1개와 단추 컨트롤 6개를 추가합니다.

    참고

    도구 상자를 보려면 보기 메뉴에서 도구 상자를 클릭합니다.

  8. 속성 창에서 다음과 같이 위치, 이름, 크기, TabIndex 및 이러한 컨트롤의 텍스트 속성을 변경합니다.

    컨트롤 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 다음 코드를 사용하여 하나의 프라이빗 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 샘플을 참조하세요.