C ++เกมส์

C++ HOME บทนำ C++ C++ เริ่มต้นใช้งาน ไวยากรณ์ C++ เอาต์พุต C++ ความคิดเห็น C++ ตัวแปร C++ อินพุตผู้ใช้ C++ ประเภทข้อมูล C++ ตัวดำเนินการ C++ สตริง C++ C++ คณิตศาสตร์ C++ บูลีน เงื่อนไข C++ สวิตช์ C++ C ++ ในขณะที่วนรอบ C ++ สำหรับลูป C++ พัก/ดำเนินการต่อ อาร์เรย์ C++ การอ้างอิง C++ ตัวชี้ C++

ฟังก์ชัน C++

ฟังก์ชัน C++ พารามิเตอร์ฟังก์ชัน C++ ฟังก์ชัน C++ โอเวอร์โหลด

คลาส C++

C++ OOP C++ คลาส/วัตถุ วิธีการคลาส C ++ ตัวสร้าง C++ ตัวระบุการเข้าถึง C++ การห่อหุ้ม C++ มรดก C++ C++ Polymorphism ไฟล์ C++ ข้อยกเว้น C++

C++ วิธีการ

เพิ่มสองตัวเลข

ตัวอย่างภาษา C++

ตัวอย่างภาษา C++ คอมไพเลอร์ C++ แบบฝึกหัด C++ แบบทดสอบ C++


ไฟล์ C++


ไฟล์ C++

ไลบรารีช่วย ให้fstreamเราทำงานกับไฟล์ได้

ในการใช้fstreamไลบรารี ให้รวมทั้งไฟล์มาตรฐาน<iostream> และส่วน<fstream>หัว:

ตัวอย่าง

#include <iostream>
#include <fstream>

มีสามคลาสที่รวมอยู่ในfstreamไลบรารี ซึ่งใช้ในการสร้าง เขียน หรืออ่านไฟล์:

Class Description
ofstream Creates and writes to files
ifstream Reads from files
fstream A combination of ofstream and ifstream: creates, reads, and writes to files

สร้างและเขียนลงในไฟล์

ในการสร้างไฟล์ ให้ใช้ the ofstreamหรือfstreamclass และระบุชื่อไฟล์

ในการเขียนไฟล์ ให้ใช้ตัวดำเนินการแทรก ( <<)

ตัวอย่าง

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

ทำไมเราถึงปิดไฟล์?

ถือเป็นแนวทางปฏิบัติที่ดีและสามารถล้างพื้นที่หน่วยความจำที่ไม่จำเป็นได้


อ่านไฟล์

หากต้องการอ่านจากไฟล์ ให้ใช้ the ifstreamหรือfstream class และชื่อไฟล์

โปรดทราบว่าเรายังใช้whileลูปร่วมกับgetline()ฟังก์ชัน (ซึ่งเป็นของifstreamคลาส) เพื่ออ่านไฟล์ทีละบรรทัด และเพื่อพิมพ์เนื้อหาของไฟล์:

ตัวอย่าง

// 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();