在 C++编程中,我们使用的是 iostream 标准库,它提供了 cin 和 cout 方法分别用于从输入读取和写入到输出。
要从文件中读取和写入文件,我们使用的是称为 fstream 的标准C++库。让我们看看在fstream库中定义的数据类型是:
数据类型 | 说明 |
---|---|
fstream | 它用于创建文件,将信息写入文件以及从文件读取信息。 |
ifstream | 它用于从文件中读取信息。 |
ofstream | 它用于创建文件并将信息写入文件。 |
让我们看一个使用C++ FileStream编程写入文本文件 testout.txt 的简单示例。
#include <iostream> #include <fstream> using namespace std; int main () { ofstream filestream("testout.txt"); if (filestream.is_open()) { filestream << "Welcome to learnfk.\n"; filestream << "C++ Tutorial.\n"; filestream.close(); } else cout <<"File opening is fail."; return 0; }
输出:
The content of a text file testout.txt is set with the data: Welcome to learnfk. C++ Tutorial.
让我们看一个使用C++ FileStream编程从文本文件 testout.txt 中读取的简单示例。
#include <iostream> #include <fstream> using namespace std; int main () { string srg; ifstream filestream("testout.txt"); if (filestream.is_open()) { while ( getline (filestream,srg) ) { cout << srg <<endl; } filestream.close(); } else { cout << "File opening is fail."<<endl; } return 0; }
输出:
Welcome to learnfk. C++ Tutorial.
让我们看一个简单的示例,将数据写入文本文件 testout.txt ,然后使用C++ FileStream编程从文件中读取数据。
#include <fstream> #include <iostream> using namespace std; int main () { char input[75]; ofstream os; os.open("testout.txt"); cout <<"Writing to a text file:" << endl; cout << "Please Enter your name: "; cin.getline(input, 100); os << input << endl; cout << "Please Enter your age: "; cin >> input; cin.ignore(); os << input << endl; os.close(); ifstream is; string line; is.open("testout.txt"); cout << "Reading from a text file:" << endl; while (getline (is,line)) { cout << line << endl; } is.close(); return 0; }
输出:
Writing to a text file: Please Enter your name: Nakul Jain Please Enter your age: 22 Reading from a text file: Nakul Jain 22
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)