Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ เพิ่มเนื้อหาของไฟล์ข้อความหนึ่งไปยังอีกไฟล์

นี่คือโปรแกรม C++ สำหรับเพิ่มเนื้อหาของไฟล์ข้อความหนึ่งไปยังอีกไฟล์หนึ่ง

ข้อมูลนำเข้า (Input)

ไฟล์ a.txt มีเนื้อหา "Tutorials"
ไฟล์ a1.txt มีเนื้อหา "point"

ผลลัพธ์ (Output)

Tutorialspoint

อัลกอริทึม

เริ่มต้น
  กำหนดอ็อบเจ็กต์ fstream ชื่อ fin
  เปิดไฟล์นำเข้า a.txt ด้วย input file stream fin
  เปิดไฟล์ปลายทาง a1.txt ด้วย output file stream fout ในโหมด append
  ตรวจสอบถ้าไฟล์ไม่มีอยู่ แสดง "File not found"
  ไม่เช่นนั้น ให้ append เนื้อหาจาก fin ไป fout
  เปิดไฟล์ปลายทางในโหมดอ่าน
  แสดงเนื้อหาเป็นผลลัพธ์
สิ้นสุด

ตัวอย่างโค้ด

#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;
}

ผลลัพธ์

Tutorialspoint