ไฟล์ 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
หรือfstream
class และระบุชื่อไฟล์
ในการเขียนไฟล์ ให้ใช้ตัวดำเนินการแทรก ( <<
)
ตัวอย่าง
#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();