Đây là chương trình C++ thêm nội dung của một file text vào file khác.
Đầu vào
a.txt chứa "Tutorials" a1.txt chứa "point"
Đầu ra
Tutorialspoint
Thuật toán
Bắt đầu
Định nghĩa đối tượng fstream fin.
Mở file input a.txt với ifstream fin.
Mở file output a1.txt với ofstream fout ở chế độ append.
Kiểm tra nếu file không tồn tại thì
In "File not found".
Ngược lại thêm nội dung từ fin vào fout.
Mở file đích ở chế độ đọc.
Hiển thị nội dung làm đầu ra.
Kết thúc.
Mã ví dụ
#include <bits/stdc++.h>
#include <fstream>
using namespace std;
int main() {
fstream f;
ifstream fin;
fin.open("a.txt");
ofstream fout;
fout.open("a1.txt", ios::app);
if (!fin.is_open()) {
cout << "Tutorialspoint";
} else {
fout << fin.rdbuf();
}
string word;
f.open("a1.txt");
while (f >> word) {
cout << word << " ";
}
return 0;
}
Kết quả
Tutorialspoint