简体   繁体   English

C ++ fstream变量

[英]C++ fstream variable

please, what contains the fstream variable? 请问,什么包含fstream变量? A can find many tutorials on fstream, but no ona actually says what is the fstream file; A可以在fstream上找到许多教程,但没有ona真正说出什么是fstream文件; declaration in the beginning. 声明的开头。 Thanks. 谢谢。

An fstream object is used to open a file for input (ie reading the contents of the file) and output (ie writing to the file). fstream对象用于打开文件以供输入(即读取文件的内容)和输出(即写入文件)。

There are also ifstream and ofstream objects, which separate input and output into two different objects. 还有ifstream和ofstream对象,它们将输入和输出分成两个不同的对象。 This is useful if, for example, you wanted to read an unformatted file and write the formatted output to a different file. 例如,如果您想读取一个未格式化的文件并将格式化后的输出写入另一个文件,这将很有用。

The fstream class is an object that handles file input and output. fstream类是一个处理文件输入和输出的对象。 It is mostly equivalent to both an ifstream and ostream object in one, in that you can use it for both input and output. 它几乎等效于一个ifstream对象和一个ostream对象,因为您可以将其同时用于输入和输出。 This tiny demonstration will create a file and write data to it. 这个小小的演示将创建一个文件并向其中写入数据。

#include <fstream>
using namespace std;

int main()
{
fstream myFile;
myFile.open("data.txt");
myFile << "This will appear in the file.";
myFile.close();
}

What is cool about fstream objects is that you can use them to read and write binary memory images to files (to protect your file's data from editing) and set various flags to control the way in which the fstream processes input and output. fstream对象最酷的地方是您可以使用它们来读取二进制内存映像并将其写入文件(以防止文件数据被编辑),并设置各种标志来控制fstream处理输入和输出的方式。 For example: 例如:

This fstream is an output stream that clears fout.txt's data and writes in binary. 该fstream是一个输出流,它清除fout.txt的数据并以二进制形式写入。

fstream foutOne("fout.txt", ios::binary | ios::out | ios::trunc)

This fstream is an output stream that does not clear fout.txt's data, but appends to the end of it instead, and writes in binary. 这个fstream是一个输出流,它不会清除fout.txt的数据,而是附加到它的末尾,并以二进制形式写入。

fstream foutTwo("fout.txt", ios::binary | ios::out | ios::app)

If I remember right, foutTwo will crash if fout.txt does not exist, while foutOne will not. 如果我没记错的话,如果fout.txt不存在,则foutTwo将崩溃,而foutOne将不崩溃。 You can (and should ALWAYS) check if the fstream loaded correctly immediately after opening a file like so: 您可以(并且应该始终)在打开文件后立即检查fstream是否正确加载:

if(!foutTwo)
{ cout << "File open error!\n"; exit(EXIT_FAILURE); }

std::fstream is a class that incapsulates the read/write access to a file. std :: fstream是一个封装对文件的读/写访问权限的类。 It inherits from iostream, so it sports all the usual methods provided by all the C++ streams to read and write to the file. 它继承自iostream,因此它采用所有C ++流提供的所有常用方法来读写文件。 For more information see its documentation and the chapter about IO of your C++ manual. 有关更多信息,请参见其文档以及C ++手册中有关IO的章节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM