Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does fstream work? Memory or file?

I'm not finding a clear answer to one aspect of the fstream object necessary to determine whether it is worth using. Does fstream store its contents in memory, or is it more like a pointer to a location in a file? I was originally using CFile and reading the text into a CString, but I'd rather not have the entire file in memory if I can avoid it.

like image 518
Joe M Avatar asked Jun 10 '13 17:06

Joe M


People also ask

How does fstream work in C++?

The fstream class deals with input from a file to a C++ program and output from the program to the file. In order to use the C++ fstream, an object from the class has to be instantiated. The stream object then has to be opened for input or output or both.

For what purpose we will use fstream?

fstream: This Stream class can be used for both read and write from/to files.

Is fstream a header file?

The classes ofstream, ifstream, and fstream are designed exclusively to manage the disk files and their declaration are present in the header file “fstream. h”. To make use of these classes, fstream. h is included in all the programs which handle disk files.


1 Answers

fstream is short for file stream -- it's normally a connection to a file in the host OS's file system. (§27.9.1.1/1: "The class basic_filebuf<charT,traits> associates both the input sequence and the output sequence with a file.")

It does (normally) buffer some information from that file, and if you happen to be working with a tiny file, it might all happen to fit in the buffer. In a typical case, however, most of the data will be in a file on disk (or at least in the OS's file cache) with some relatively small portion of it (typically a few kilobytes) in the fstream's buffer.

If you did want to use a buffer in memory and have it act like a file, you'd normally use a std::stringstream (or a variant like std::istringstream or std::ostringstream).

like image 182
Jerry Coffin Avatar answered Sep 24 '22 02:09

Jerry Coffin