Files Trong C++

Files Trong C++
Rate this post

C++ Files

Thư viện fstream cho phép chúng tôi làm việc với các tệp.

Để sử dụng thư viện fstream, hãy bao gồm cả tệp tiêu đề <iostream> VÀ <fstream> chuẩn:

Example

#include <iostream>
#include <fstream>

Có ba lớp được bao gồm trong thư viện fstream, được sử dụng để tạo, ghi hoặc đọc tệp:

Lớp Sự mô tả
ofstream Tạo và ghi vào tệp
ifstream Đọc từ tệp
fstream Sự kết hợp giữa ofstream và ifstream: tạo, đọc và ghi vào tệp

Tạo Và Ghi Vào Tệp

Để tạo tệp, hãy sử dụng lớp ofstream hoặc fstream và chỉ định tên của tệp.

Để ghi vào tệp, hãy sử dụng toán tử chèn (<<).

Example

#include <iostream>
#include <fstream>
using namespace std;

int main() {
  // Create and open a text file
  ofstream MyFile("filename.txt");

  // Write to the file
  MyFile << "Files can be tricky, but it is fun enough!";

  // Close the file
  MyFile.close();
}

Đọc Tệp

Để đọc từ một tệp, hãy sử dụng lớp ifstream hoặc fstream và tên của tệp.

Lưu ý rằng chúng ta cũng sử dụng vòng lặp while cùng với hàm getline () (thuộc về lớp ifstream) để đọc từng dòng của tệp và in nội dung của tệp:

Example

// Create a text string, which is used to output the text file
string myText;

// Read from the text file
ifstream MyReadFile("filename.txt");

// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) {
  // Output the text from the file
  cout << myText;
}

// Close the file
MyReadFile.close();

 

0 / 5 - (0 Đánh Giá)

Leave a Reply

Your email address will not be published. Required fields are marked *

PHP Code Snippets Powered By : XYZScripts.com
.
.
.
.