Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Cách thêm văn bản vào file text trong C++

Đây là chương trình C++ thêm văn bản vào file text.

Thuật toán

Bắt đầu
  Mở file a1.txt dưới dạng output file stream để thực hiện ghi ở chế độ append dùng fout.
  Nếu file tồn tại thì
    Thêm văn bản vào file đó.
  Đóng fout.
  Mở file "a1.txt" đọc nội dung.
  Trích xuất văn bản từ file và in ra. 
Kết thúc.

Mã ví dụ

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

int main() {
    fstream f;
    ofstream fout;
    ifstream fin;
    fin.open("a1.txt");
    fout.open("a1.txt", ios::app);
    if(fin.is_open())
        fout << " tutorials point";
        cout << "\n Dữ liệu đã được thêm vào file" << endl;
        fin.close();
        fout.close();
        string word;
        f.open("a1.txt");
        while (f >> word) {
            cout << word << " ";
        }
        return 0;
    }
}

Kết quả

Dữ liệu đã được thêm vào file