ملفات 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 |
إنشاء ملف والكتابة إليه
لإنشاء ملف ، استخدم الفئة ofstream
أو fstream
، وحدد اسم الملف.
للكتابة إلى الملف ، استخدم عامل الإدخال ( <<
).
مثال
#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();
}
لماذا نغلق الملف؟
تعتبر ممارسة جيدة ، ويمكنها تنظيف مساحة الذاكرة غير الضرورية.
اقرأ ملفًا
للقراءة من ملف ، استخدم الفئة ifstream
أو fstream
واسم الملف.
لاحظ أننا نستخدم أيضًا 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();