Visual C++'da temel dosya G/Ç'sini yapma
Bu makalede, Microsoft Visual C++ veya Visual C++ .NET'te temel dosya giriş/çıkış (G/Ç) işlemlerinin nasıl gerçekleştirildiği açıklanır.
Orijinal ürün sürümü: Visual C++
Özgün KB numarası: 307398
Özet
.NET Framework yeniyseniz, .NET Framework dosya işlemleri için nesne modelinin birçok Visual Studio geliştiricisi tarafından popüler olan modele FileSystemObject
benzer olduğunu göreceksiniz.
Geçişi kolaylaştırmak için bkz. Visual Basic ile FileSystemObject Kullanma.
Bu makalenin Visual C# .NET sürümü için bkz. Visual C#'de temel dosya G/Ç'sini yapma.
Bu makale, aşağıdaki .NET Framework Sınıf Kitaplığı ad alanlarını ifade eder:
System::ComponentModel
System::Windows::Forms
System::Drawing
yine de .NET Framework kullanabilirsinizFileSystemObject
. FileSystemObject
bir Bileşen Nesne Modeli (COM) bileşeni olduğundan, .NET Framework nesneye erişimin Birlikte Çalışma katmanı üzerinden olmasını gerektirir. .NET Framework, kullanmak istiyorsanız bileşen için bir sarmalayıcı oluşturur. Bununla birlikteFile
, sınıfı, FileInfo
sınıfı, Directory
, DirectoryInfo
sınıfları ve .NET Framework diğer ilgili sınıflar, Birlikte Çalışma katmanının ek yükü olmadan ile FileSystemObject
kullanılamayabilecek işlevler sunar.
Dosya G/Ç işlemleri gösterildi
Bu makaledeki örneklerde temel dosya G/Ç işlemleri açıklanmaktadır. Adım adım örnek bölümünde, aşağıdaki altı dosya G/Ç işlemini gösteren örnek bir programın nasıl oluşturulacağı açıklanır:
- Metin dosyası okuma
- Metin dosyası yazma
- Dosya bilgilerini görüntüleme
- Disk sürücülerini listeleme
- Alt klasörleri listeleme
- Dosyaları listeleme
Metin dosyası okuma
Aşağıdaki örnek kod, metin dosyasını okumak için bir StreamReader
sınıf kullanır. Dosyanın içeriği listbox denetimine eklenir. Blok try...catch
, dosya boşsa programı uyarmak için kullanılır. Dosyanın sonuna ulaşıldığında belirlemenin birçok yolu vardır; Bu örnek, okumadan önce sonraki satırı incelemek için yöntemini kullanır 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++'da, önceki kod örneğini yönetilen C++ olarak başarıyla derlemek için ortak dil çalışma zamanı desteği derleyici seçeneğini (/clr:oldSyntax) eklemeniz gerekir. Ortak dil çalışma zamanı desteği derleyici seçeneğini eklemek için şu adımları izleyin:
Project'e ve ardından ProjectName> Özellikleri'ne tıklayın<.
Not
<ProjectName> , projenin adı için bir yer tutucudur.
Yapılandırma Özellikleri'ni genişletin ve genel'e tıklayın.
Sağ bölmede, Ortak Dil Çalışma Zamanı destek projesi ayarlarında Ortak Dil Çalışma Zamanı Desteği, Eski Söz Dizimi (/clr:oldSyntax) öğesini seçmek için tıklayın.
Uygula'yı ve ardından Tamam'ı tıklatın.
Metin dosyası yazma
Bu örnek kod, dosya StreamWriter
oluşturmak ve dosyaya yazmak için bir sınıf kullanır. Mevcut bir dosyanız varsa, dosyayı aynı şekilde açabilirsiniz.
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);
Dosya bilgilerini görüntüleme
Bu örnek kod, bir FileInfo
dosyanın özelliklerine erişmek için bir sınıf kullanır. Notepad.exe bu örnekte kullanılır. Özellikler bir ListBox denetiminde görünür.
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()));
Disk sürücülerini listeleme
Bu örnek kod, sistemdeki Directory
mantıksal sürücüleri listelemek için ve Drive
sınıflarını kullanır. Bu örnek için sonuçlar ListBox denetiminde görünür.
listBox1->Items->Clear();
String* drives[] = Directory::GetLogicalDrives();
int numDrives = drives->get_Length();
for (int i=0; i<numDrives; i++)
{
listBox1->Items->Add(drives[i]);
}
Alt klasörleri listeleme
Bu örnek kod, klasörlerin GetDirectories
Directory
listesini almak için sınıfının yöntemini kullanır.
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]);
}
Dosyaları listeleme
Bu örnek kod, dosyaların listesini almak için sınıfının yöntemini Directory
kullanırGetFiles
.
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]);
}
Kullanıcı dosyalara eriştiğinde birçok sorun oluşabilir. Dosyalar mevcut olmayabilir, dosyalar kullanımda olabilir veya kullanıcıların erişmeye çalıştıkları klasör dosyaları üzerinde hakları olmayabilir. Oluşturulabilecek özel durumları işlemek için kod yazarken bu olasılıkları göz önünde bulundurun.
Adım adım örnek
Visual Studio .NET'i başlatın.
Dosya menüsünde, Yeni'nin üzerine gelin ve Proje'ye tıklayın.
Proje Türleri'nin altında Visual C++ Projeleri'ne tıklayın. Şablonlar bölümünde Uygulama (.NET) Windows Forms'e tıklayın.
Ad kutusuna KB307398 yazın, Konum kutusuna yazın
C:\
ve tamam'a tıklayın.Form1 formunu Tasarım görünümünde açın ve ardından F4 tuşuna basarak Özellikler penceresini açın.
Özellikler penceresinde Boyut klasörünü genişletin. Genişlik kutusuna 700 yazın. Yükseklik kutusuna 320 yazın.
Form1'e bir ListBox denetimi ve altı Düğme denetimi ekleyin.
Not
Araç kutusunu görüntülemek için Görünüm menüsünde Araç Kutusu'na tıklayın.
Özellikler penceresinde Konum, Ad, Boyut, TabIndex ve bu denetimlerin Metin özelliklerini aşağıdaki gibi değiştirin:
Denetim Kimliği Konum Name Boyut Tabındex Metin düğme1 500, 32 düğme1 112, 23 1 Metin Dosyasını Oku düğme2 500, 64 düğme2 112, 23 2 Metin Dosyası Yazma düğme3 500, 96 düğme3 112, 23 3 Dosya Bilgilerini Görüntüle düğme4 500, 128 düğme4 112, 23 4 Sürücüleri Listeleme düğme5 500, 160 düğme5 112, 23 5 Liste Alt Klasörleri düğme6 500, 192 düğme6 112, 23 6 Liste Dosyaları listBox1 24, 24 listBox1 450, 200 0 listBox1 Form1.h dosyasını açın. Sınıf bildiriminde
Form1
aşağıdaki kodla bir özelString
değişken bildirin:private: String *windir;
Sınıf oluşturucusunda
Form1
aşağıdaki kodu ekleyin:windir = System::Environment::GetEnvironmentVariable("windir");
Giriş çıkış işlemleri dosyası yapmak için ad alanını
System::IO
ekleyin.Form1'i Tasarım görünümünde açmak için SHIFT+F7 tuşlarına basın. Metin Dosyasını Oku düğmesine çift tıklayın ve aşağıdaki kodu yapıştırın:
// 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 Tasarım görünümünde , Metin Dosyası Yaz düğmesine çift tıklayın ve aşağıdaki kodu yapıştırın:
// 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 Tasarım görünümünde Dosya Bilgilerini Görüntüle düğmesine çift tıklayın ve aşağıdaki kodu yöntemine yapıştırın:
// 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 Tasarım görünümünde Sürücüleri Listele düğmesine çift tıklayın ve aşağıdaki kodu yapıştırın:
// 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 Tasarım görünümünde, Liste Alt Klasörleri düğmesine çift tıklayın ve aşağıdaki kodu yapıştırın:
// 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 Tasarım görünümünde, Dosyaları Listele düğmesine çift tıklayın ve aşağıdaki kodu yapıştırın:
// 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]); }
Programı derlemek ve çalıştırmak için CTRL+F5 tuşlarına basın.
Tam kod örneği
//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;
}
Başvurular
Daha fazla bilgi için Microsoft Desteği ziyaret edin. C++ için yönetilen uzantılarda Windows formları oluşturma hakkında daha fazla bilgi için Visual Studio .NET Yardımı'ndaki örne bakın ManagedCWinFormWiz
.
Geri Bildirim
https://aka.ms/ContentUserFeedback.
Çok yakında: 2024 boyunca, içerik için geri bildirim mekanizması olarak GitHub Sorunları’nı kullanımdan kaldıracak ve yeni bir geri bildirim sistemiyle değiştireceğiz. Daha fazla bilgi için bkz.Gönderin ve geri bildirimi görüntüleyin