本文概述
在C ++编程中, 我们使用iostream标准库, 它提供了cin和cout方法, 分别用于从输入读取和写入到输出。
要从文件中读取和写入文件, 我们使用称为fstream的标准C ++库。让我们看看在fstream库中定义的数据类型是:
数据类型 | 描述 |
---|---|
fstream | 它用于创建文件, 将信息写入文件以及从文件读取信息。 |
ifstream | 它用于从文件读取信息。 |
ofstream | 它用于创建文件并将信息写入文件。 |
C ++ FileStream示例:写入文件
让我们看一个使用C ++ FileStream编程写入文本文件testout.txt的简单示例。
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream filestream("testout.txt");
if (filestream.is_open())
{
filestream << "Welcome to srcmini.\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 srcmini.
C++ Tutorial.
C ++ FileStream示例:从文件读取
让我们看一个使用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;
}
注意:在运行代码之前, 需要创建一个名为“ testout.txt”的文本文件, 并且在下面给出文本文件的内容:欢迎使用srcmini。 C ++教程。
输出:
Welcome to srcmini.
C++ Tutorial.
C ++读写示例
让我们看一个简单的示例, 将数据写入文本文件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
评论前必须登录!
注册