Include fstream c что это
БлогNot. Лекции по C/C++: работа с файлами (fstream)
Лекции по C/C++: работа с файлами (fstream)
Механизм ввода-вывода, разработанный для обычного языка С, не соответствует общепринятому сегодня стилю объектно-ориентированного программирования, кроме того, он активно использует операции с указателями, считающиеся потенциально небезопасными в современных защищённых средах выполнения кода. Альтернативой при разработке прикладных приложений является механизм стандартных классов ввода-вывода, предоставляемый стандартом языка C++.
Открытие файлов
Наиболее часто применяются классы ifstream для чтения, ofstream для записи и fstream для модификации файлов.
Все поточные классы ввода-вывода являются косвенными производными от общего предка ios , полностью наследуя его функциональность. Так, режим открытия файлов задает член данных перечисляемого типа open_mode, который определяется следующим образом:
Ниже приведены возможные значения флагов и их назначение.
| Режим | Назначение |
| in | Открыть для ввода (выбирается по умолчанию для ifstream) |
| out | Открыть для вывода (выбирается по умолчанию для ofstream) |
| binary | Открыть файл в бинарном виде |
| aрр | Присоединять данные; запись в конец файла |
| ate | Установить файловый указатель на конец файла |
| trunc | Уничтожить содержимое, если файл существует (выбирается по умолчанию, если флаг out указан, а флаги ate и арр — нет) |
Например, чтобы открыть файл с именем test.txt для чтения данных в бинарном виде, следует написать:
Оператор логического ИЛИ ( | ) позволяет составить режим с любым сочетанием флагов. Так, чтобы, открывая файл по записи, случайно не затереть существующий файл с тем же именем, надо использовать следующую форму:
Предполагается, что к проекту подключён соответствующий заголовочный файл:
Для проверки того удалось ли открыть файл, можно применять конструкцию
Операторы включения и извлечения
Переопределённый в классах работы с файлами оператор включения ( << ) записывает данные в файловый поток. Как только вы открыли файл для записи, можно записывать в него текстовую строку целиком:
Можно также записывать текстовую строку по частям:
Оператор endl завершает ввод строки символом «возврат каретки»:
С помощью оператора включения несложно записывать в файл значения переменных или элементов массива:
В результате выполнения кода образуется три строки текстового файла Temp.txt :
Обратите внимание, что числовые значения записываются в файл в виде текстовых строк, а не двоичных значений.
Оператор извлечения ( >> )производит обратные действия. Казалось бы, чтобы извлечь символы из файла Temp.txt , записанного ранее, нужно написать код наподобие следующего:
Однако оператор извлечения остановится на первом попавшемся разделителе (символе пробела, табуляции или новой строки). Таким образом, при разборе предложения «Текстовый массив содержит переменные» только слово «Текстовый» запишется в массив buff , пробел игнорируется, а слово «массив» станет значением целой переменной vx и исполнение кода «пойдет вразнос» с неминуемым нарушением структуры данных. Далее, при обсуждении класса ifstream , будет показано, как правильно организовать чтение файла из предыдущего примера.
Класс ifstream: чтение файлов
Как следует из расшифровки названия, класс ifstream предназначен для ввода файлового потока. Далее перечислены основные методы класса. Большая часть из них унаследована от класса istream и перегружена с расширением родительской функциональности. К примеру, функция get , в зависимости от параметра вызова, способна считывать не только одиночный символ, но и символьный блок.
| Метод | Описание |
| open | Открывает файл для чтения |
| get | Читает один или более символов из файла |
| getline | Читает символьную строку из текстового файла или данные из бинарного файла до определенного ограничителя |
| read | Считывает заданное число байт из файла в память |
| eof | Возвращает ненулевое значение (true), когда указатель потока достигает конца файла |
| peek | Выдает очередной символ потока, но не выбирает его |
| seekg | Перемещает указатель позиционирования файла в заданное положение |
| tellg | Возвращает текущее значение указателя позиционирования файла |
| close | Закрывает файл |
Теперь понятно, как нужно модифицировать предыдущий пример, чтобы использование оператора извлечения данных давало ожидаемый результат:
Метод getline прочитает первую строку файла до конца, а оператор >> присвоит значения переменным.
Следующий пример показывает добавление данных в текстовый файл с последующим чтением всего файла. Цикл while (1) используется вместо while(!file2.eof()) по причинам, которые обсуждались в предыдущей лекции.
Этот код под ОС Windows также зависит от наличия в последней строке файла символа перевода строки, надежнее было бы сделать так:
Явные вызовы методов open и close не обязательны. Действительно, вызов конструктора с аргументом позволяет сразу же, в момент создания поточного объекта file , открыть файл:
Вместо метода close можно использовать оператор delete , который автоматически вызовет деструктор объекта file и закроет файл. Код цикла while обеспечивает надлежащую проверку признака конца файла.
Класс ofstream: запись файлов
Класс ofstream предназначен для вывода данных из файлового потока. Далее перечислены основные методы данного класса.
| Метод | Описание |
| open | Открывает файл для записи |
| put | Записывает одиночный символ в файл |
| write | Записывает заданное число байт из памяти в файл |
| seekp | Перемещает указатель позиционирования в указанное положение |
| tellp | Возвращает текущее значение указателя позиционирования файла |
| close | Закрывает файл |
Описанный ранее оператор включения удобен для организации записи в текстовый файл:
Бинарные файлы
В принципе, бинарные данные обслуживаются наподобие текстовых. Отличие состоит в том, что если бинарные данные записываются в определенной логической структуре, то они должны считываться из файла в переменную того же структурного типа.
Первый параметр методов write и read (адрес блока записи/чтения) должен иметь тип символьного указателя char * , поэтому необходимо произвести явное преобразование типа адреса структуры void * . Второй параметр указывает, что бинарные блоки файла имеют постоянный размер байтов независимо от фактической длины записи. Следующее приложение дает пример создания и отображения данных простейшей записной книжки. Затем записи файла последовательно считываются и отображаются на консоли.
P.S. При выполнении этого и других листингов в Visual Studio последних версий может дополнительно понадобиться подключение директивы _CRT_SECURE_NO_WARNINGS.
В результате выполнения этого кода образуется бинарный файл Notebook.dat из трех блоков размером по 80 байт каждый (при условии, что символы — однобайтовые). Естественно, вы можете использовать другие поточные методы и проделывать любые операции над полями определенной структуры данных.
Класс fstream: произвольный доступ к файлу
Предположим что в нашей записной книжке накопилось 100 записей, а мы хотим считать 50-ю. Конечно, можно организовать цикл и прочитать все записи с первой по заданную. Очевидно, что более целенаправленное решение — установить указатель позиционирования файла pos прямо на запись 50 и считать ее:
Подобные операции поиска эффективны, если файл состоит из записей известного и постоянного размера. Чтобы заменить содержимое произвольной записи, надо открыть поток вывода в режиме модификации:
Если не указать флаг ios::ate (или ios::app ), то при открытии бинарного файла Notebook.dat его предыдущее содержимое будет стерто!
Дополнительно может понадобиться указать, откуда отсчитывается смещение.
Наконец, можно открыть файл одновременно для чтения/записи, используя методы, унаследованные поточным классом fstream от своих предшественников. Поскольку класс fstream произведен от istream и ostream (родителей ifstream и ofstream соответственно), все упомянутые ранее методы становятся доступными в приложении.
Input/output with files
C++ provides the following classes to perform output and input of characters to/from files:
- ofstream : Stream class to write on files
- ifstream : Stream class to read from files
- fstream : Stream class to both read and write from/to files.
This code creates a file called example.txt and inserts a sentence into it in the same way we are used to do with cout , but using the file stream myfile instead.
But let’s go step by step:
Open a file
The first operation generally performed on an object of one of these classes is to associate it to a real file. This procedure is known as to open a file. An open file is represented within a program by a stream (i.e., an object of one of these classes; in the previous example, this was myfile ) and any input or output operation performed on this stream object will be applied to the physical file associated to it.
In order to open a file with a stream object we use its member function open :
open (filename, mode);
Where filename is a string representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags:
| ios::in | Open for input operations. |
| ios::out | Open for output operations. |
| ios::binary | Open in binary mode. |
| ios::ate | Set the initial position at the end of the file. If this flag is not set, the initial position is the beginning of the file. |
| ios::app | All output operations are performed at the end of the file, appending the content to the current content of the file. |
| ios::trunc | If the file is opened for output operations and it already existed, its previous content is deleted and replaced by the new one. |
All these flags can be combined using the bitwise operator OR ( | ). For example, if we want to open the file example.bin in binary mode to add data we could do it by the following call to member function open :
Each of the open member functions of classes ofstream , ifstream and fstream has a default mode that is used if the file is opened without a second argument:
| class | default mode parameter |
|---|---|
| ofstream | ios::out |
| ifstream | ios::in |
| fstream | ios::in | ios::out |
For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively assumed, even if a mode that does not include them is passed as second argument to the open member function (the flags are combined).
For fstream , the default value is only applied if the function is called without specifying any value for the mode parameter. If the function is called with any value in that parameter the default mode is overridden, not combined.
File streams opened in binary mode perform input and output operations independently of any format considerations. Non-binary files are known as text files, and some translations may occur due to formatting of some special characters (like newline and carriage return characters).
Since the first task that is performed on a file stream is generally to open a file, these three classes include a constructor that automatically calls the open member function and has the exact same parameters as this member. Therefore, we could also have declared the previous myfile object and conduct the same opening operation in our previous example by writing:
Combining object construction and stream opening in a single statement. Both forms to open a file are valid and equivalent.
To check if a file stream was successful opening a file, you can do it by calling to member is_open . This member function returns a bool value of true in the case that indeed the stream object is associated with an open file, or false otherwise:
Closing a file
When we are finished with our input and output operations on a file we shall close it so that the operating system is notified and its resources become available again. For that, we call the stream’s member function close . This member function takes flushes the associated buffers and closes the file:
Once this member function is called, the stream object can be re-used to open another file, and the file is available again to be opened by other processes.
In case that an object is destroyed while still associated with an open file, the destructor automatically calls the member function close .
Text files
Text file streams are those where the ios::binary flag is not included in their opening mode. These files are designed to store text and thus all values that are input or output from/to them can suffer some formatting transformations, which do not necessarily correspond to their literal binary value.
Writing operations on text files are performed in the same way we operated with cout :
Reading from a file can also be performed in the same way that we did with cin :
Checking state flags
The following member functions exist to check for specific states of a stream (all of them return a bool value):
bad() Returns true if a reading or writing operation fails. For example, in the case that we try to write to a file that is not open for writing or if the device where we try to write has no space left. fail() Returns true in the same cases as bad() , but also in the case that a format error happens, like when an alphabetical character is extracted when we are trying to read an integer number. eof() Returns true if a file open for reading has reached the end. good() It is the most generic state flag: it returns false in the same cases in which calling any of the previous functions would return true . Note that good and bad are not exact opposites ( good checks more state flags at once).
The member function clear() can be used to reset the state flags.
get and put stream positioning
All i/o streams objects keep internally -at least- one internal position:
ifstream , like istream , keeps an internal get position with the location of the element to be read in the next input operation.
ofstream , like ostream , keeps an internal put position with the location where the next element has to be written.
Finally, fstream , keeps both, the get and the put position, like iostream .
These internal stream positions point to the locations within the stream where the next reading or writing operation is performed. These positions can be observed and modified using the following member functions:
tellg() and tellp()
These two member functions with no parameters return a value of the member type streampos , which is a type representing the current get position (in the case of tellg ) or the put position (in the case of tellp ).
seekg() and seekp()
These functions allow to change the location of the get and put positions. Both functions are overloaded with two different prototypes. The first form is:
seekg ( position );
seekp ( position );
Using this prototype, the stream pointer is changed to the absolute position position (counting from the beginning of the file). The type for this parameter is streampos , which is the same type as returned by functions tellg and tellp .
The other form for these functions is:
seekg ( offset, direction );
seekp ( offset, direction );
Using this prototype, the get or put position is set to an offset value relative to some specific point determined by the parameter direction . offset is of type streamoff . And direction is of type seekdir , which is an enumerated type that determines the point from where offset is counted from, and that can take any of the following values:
| ios::beg | offset counted from the beginning of the stream |
| ios::cur | offset counted from the current position |
| ios::end | offset counted from the end of the stream |
The following example uses the member functions we have just seen to obtain the size of a file:
Notice the type we have used for variables begin and end :
streampos is a specific type used for buffer and file positioning and is the type returned by file.tellg() . Values of this type can safely be subtracted from other values of the same type, and can also be converted to an integer type large enough to contain the size of the file.
These stream positioning functions use two particular types: streampos and streamoff . These types are also defined as member types of the stream class:
| Type | Member type | Description |
|---|---|---|
| streampos | ios::pos_type | Defined as fpos<mbstate_t> . It can be converted to/from streamoff and can be added or subtracted values of these types. |
| streamoff | ios::off_type | It is an alias of one of the fundamental integral types (such as int or long long ). |
Each of the member types above is an alias of its non-member equivalent (they are the exact same type). It does not matter which one is used. The member types are more generic, because they are the same on all stream objects (even on streams using exotic types of characters), but the non-member types are widely used in existing code for historical reasons.
Binary files
For binary files, reading and writing data with the extraction and insertion operators ( << and >> ) and functions like getline is not efficient, since we do not need to format any data and data is likely not formatted in lines.
File streams include two member functions specifically designed to read and write binary data sequentially: write and read . The first one ( write ) is a member function of ostream (inherited by ofstream ). And read is a member function of istream (inherited by ifstream ). Objects of class fstream have both. Their prototypes are:
write ( memory_block, size );
read ( memory_block, size );
Where memory_block is of type char* (pointer to char ), and represents the address of an array of bytes where the read data elements are stored or from where the data elements to be written are taken. The size parameter is an integer value that specifies the number of characters to be read or written from/to the memory block.
In this example, the entire file is read and stored in a memory block. Let’s examine how this is done:
First, the file is open with the ios::ate flag, which means that the get pointer will be positioned at the end of the file. This way, when we call to member tellg() , we will directly obtain the size of the file.
Once we have obtained the size of the file, we request the allocation of a memory block large enough to hold the entire file:
Right after that, we proceed to set the get position at the beginning of the file (remember that we opened the file with this pointer at the end), then we read the entire file, and finally close it:
Buffers and Synchronization
When we operate with file streams, these are associated to an internal buffer object of type streambuf . This buffer object may represent a memory block that acts as an intermediary between the stream and the physical file. For example, with an ofstream , each time the member function put (which writes a single character) is called, the character may be inserted in this intermediate buffer instead of being written directly to the physical file with which the stream is associated.
The operating system may also define other layers of buffering for reading and writing to files.
When the buffer is flushed, all the data contained in it is written to the physical medium (if it is an output stream). This process is called synchronization and takes place under any of the following circumstances:
How to Use C++ fstream
It is possible for inputting and outputting to take place in one session. This is made possible by the class template, basic_fstream. Now, fstream is a synonym for basic_fstream. fstream, which is still basic_fstream, uses basic_ifstream and ofstream to operate.
In order to do input alone, do output alone, or both in one session, it suffices to start the C++ program with the following includes and namespace invocations:
This tutorial has four main sections: opening and closing of a file stream, output file stream, appending, input file stream, and editing a file. Editing a file means inputting and outputting a stream.
Article Content
Opening and Closing a File Stream
Before a stream can be opened, a stream object has to be created. Opening a stream means establishing a channel between the C++ program and the file in disk. This is accomplished through which the sequence of characters will move to the file; or through which sequence of characters will leave the file and come to the program; or through which characters will move to-and-fro.
A stream is opened only for writing (output), reading (input), or both reading and writing. It can also be opened for other reasons.
Before opening a stream, the stream object has to be constructed. The simplest way to express it is as follows in the C++ main() function:
Now, with the strm object, the fstream member functions, open() and close() can be used, preceding each with the dot operator. The following statement can be used to open an fstream for reading:
The open() member function returns void.
With the stream object, the statement would be:
Since the open() member function returns void, to know if the file in the disk was successfully opened, use the member function:
It returns zero for false if the file did not open and 1 for true if the file opened. Now our program looks like this so far:
#include <fstream>
#include <iostream>
using namespace std ;
int main ( ) {
fstream strm ;
strm. open ( "./myfile" , ios_base :: in ) ;
To open a file for writing, use this flag:
ios_base::in means open for reading and ios_base::out means open for writing. To open a file for reading and writing, use:
Note: the presence of “ios_base::in | ios_base::out”, which uses logical OR to combine both flags as a single argument to the function.
Closing a stream means closing the channel through which data can be sent to and fro between the program and the file. No more datum can be sent in either direction using that channel. Closing the stream is not closing the stream object. The same stream can still be used to open a new channel, which should be closed after use in transmission of data. Make it a habit of closing any file stream, after it has been opened. When a stream is closed, any data in memory that was supposed to have been in the file is sent to the file before actually closing. The member function prototype to close fstream is:
It returns void, unfortunately. So, to know whether the closing was successful, use the member function:
If the closing were successful, this would return zero, meaning the stream is no longer open. If the closing were unsuccessful, it would return 1 and meaning the stream could not be closed.
Output File Stream Operation
Now we will demonstrate opening a file and giving it new data content. To open an output stream with fsream, just use ios_base::out alone in the open() member function. The following program opens a file, and it sends the content of a string to it:
#include <fstream>
#include <iostream>
using namespace std ;
fstream strm ;
strm. open ( "doc1.txt" , ios_base :: out ) ;
if ( ! strm. is_open ( ) ) {
cout << "File could not be opened!" << endl ;
return 1 ;
}
char str [ ] = "A: This is the first line. \n "
"B: This is the second line. \n "
"C: This is the third line. \n " ;
strm << str ;
strm. close ( ) ;
if ( strm. is_open ( ) ) {
cout << "Stream could not close!" << endl ;
return 1 ;
}
cout << "Success, check file" << endl ;
return 0 ;
}
The name of the file is doc1.txt can include a full path or a relative path. The new content is identified by str in the program. At the end of the program, the string content would have been inserted into the stream and thus, the file with the statement:
Cout is a standard output object, and it is typically used for the console. It uses the extraction operator, #include <fstream>
#include <iostream>
#include <cstring>
using namespace std ;
fstream strm ;
strm. open ( "doc2.txt" , ios_base :: out ) ;
if ( ! strm. is_open ( ) ) {
cout << "File could not be opened!" << endl ;
return 1 ;
}
char str [ ] = "A: This is the first line. \n "
"B: This is the second line. \n "
"C: This is the third line. \n " ;
strm. write ( str, strlen ( str ) ) ;
The first argument of the write() function is the identifier of the character array. The second argument is the number of characters (without \0) in the array.
Appending Characters to a File
To append text to a file, use “ios_base::app” alone, instead of “ios_base::out” in the open() member function. Still, use the insertion operator, <<, as follows:
#include <fstream>
#include <iostream>
#include <cstring>
using namespace std ;
fstream strm ;
strm. open ( "doc2.txt" , ios_base :: app ) ;
if ( ! strm. is_open ( ) ) {
cout << "File could not be opened!" << endl ;
return 1 ;
}
char str [ ] = "D: This is the fourth line. \n " ;
The output file should now have four lines.
Input File Stream Operation
Now we will demonstrate reading a file character by character with fstream. To read a file with fstream, use ios_base::in as the flag in the open() member function. The following program reads all the content of the file and displays it at the console:
#include <fstream>
#include <iostream>
using namespace std ;
int main ( )
{
fstream strm ;
strm. open ( "doc1.txt" , ios_base :: in ) ;
if ( ! strm. is_open ( ) ) {
cout << "Open file failed" << endl ;
return 1 ;
}
char c ;
The eof() is a member function, and it returns 1 when the end-of-file is reached and zero otherwise. The program reads the characters of the file, one by one, until the end-of-file is reached. It uses the get() member function, putting the read character into the variable c, which has already been declared. cout sends each character to the console. The output should be:
Reading the Whole File With One Function
The whole file can be read using the member function:
It copies characters from the file and puts them into a character array. It does this until it meets the delimiter, EOF, or until it has copied the n – 1 character. It will fit the NULL (‘\0’) character as the last consecutive character in the array. This means the number of characters chosen for the array should be estimated to be at least the number of file characters (including any \n), plus one for the NULL character. It does not copy the delimiter character. The following code copies the whole file of doc1.txt, using this member function:
#include <fstream>
#include <iostream>
using namespace std ;
int main ( )
{
fstream strm ;
strm. open ( "doc1.txt" , ios_base :: in ) ;
if ( ! strm. is_open ( ) ) {
cout << "Open file failed" << endl ;
return 1 ;
}
char arr [ 150 ] ;
strm. get ( arr, 150 , EOF ) ;
strm. close ( ) ;
Reading Line by Line
The member function to use for reading from a file with fstream line by line is:
It copies characters from the file and puts them into a character array. It does this until it meets the delimiter (e.g. ‘\n’) or until it has copied the n – 1 character. It will fit the NUL (‘\0’) character as the last consecutive character in the array. This means the number of characters chosen for the array should be estimated to be at least the number of visible characters, plus one for the null character. It does not copy the delimiter character. The following code copies the whole file of doc1.txt line by line, using this member function:
#include <fstream>
#include <iostream>
using namespace std ;
int main ( )
{
fstream strm ;
strm. open ( "doc1.txt" , ios_base :: in ) ;
if ( ! strm. is_open ( ) ) {
cout << "Open file failed" << endl ;
return 1 ;
}
char arr [ 100 ] ;
Since ‘\n’ is not copied when copying a line, endl has to be used for the output display. Note that the number of characters in the array and streamsize variable, have been made the same. If it is known in advance that the delimiter is ‘\n’ then the following member function can be used:
Seeking in the file
Characters including ‘\n’ have their natural positions in the file, beginning from 0, then 1, 2, 3, and so on. The seekg(pos) member function would point the pointer to the character of a position in the stream object. Then, get(c) can be used to obtain that character. The character in the 27 th position of the current doc1.txt file is ‘B’. The following code reads and displays it:
#include <fstream>
#include <iostream>
using namespace std ;
int main ( )
{
fstream strm ;
strm. open ( "doc1.txt" , ios_base :: in ) ;
if ( ! strm. is_open ( ) ) {
cout << "Open file failed" << endl ;
return 1 ;
}
char c ;
strm. seekg ( 27 ) ;
strm. get ( c ) ;
cout << c << endl ;
strm. close ( ) ;
If the position given is greater than that of the last character in the file (minus 1), null is returned.
tellg() function
As a file is being read, an internal pointer points to the next character to be read. The tellg() member function can get the position number of the character the pointer is pointing to. When the file is just opened, tellg() will return 0 for the first character. After reading the first line, tellg() would return a number like 27 in the example below:
#include <fstream>
#include <iostream>
using namespace std ;
int main ( )
{
fstream strm ;
strm. open ( "doc1.txt" , ios_base :: in ) ;
if ( ! strm. is_open ( ) ) {
cout << "Open file failed" << endl ;
return 1 ;
}
char arr [ 100 ] ;
int pos ;
strm. getline ( arr, 100 , ‘ \n ‘ ) ;
pos = strm. tellg ( ) ;
strm. close ( ) ;
cout << "Position in file is now: " << pos << endl ;
$ . / t9
Position in file is now : 27
The equivalent function for outputting is tellp().
seekdir
seekdir means seek direction. Its constants defined in the ios_base library are: beg for the beginning of the file, cur for the current position of the file, and end for ending of the file. The above seekg() function is overloaded for the input stream as:
So, if the internal pointer is pointing to the character at position 27 by counting the beginning from 0, then
Will maintain the pointer at the current position.
Will take the pointer 5 places ahead to point at “i” in the second “This” of the doc1.txt file.
Will take the pointer 5 places behind to point at “i” in the first “line” of the doc1.txt file. Note that the position of the newline character ‘\n’, which is not displayed at the output, is counted.
Now, no matter where the pointer might be,
Takes and maintains the pointer at the beginning of the file; to point to the first character of the file, with an offset of 0. In this case, it will point to “A”.
Will take the pointer to the beginning with an offset of 5 places ahead; point at “i” in the first “This” of the doc1.txt file. Note that the single space is counted as one character.
A negative integer in the offset position for “ios_base::beg” is not useful.
Well, no matter where the pointer might be,
Will take and maintain the pointer just after the end of the file; to point to nothing.
A positive integer in the offset position for “ios_base::end” is not useful.
Will take the pointer to the end with an offset of 5 places behind; point at “i” in the last “line” of the doc1.txt file. Note that ‘\n’ and the dot are counted as one character each.
The following code illustrates the use of the function, at the current position, with a negative and positive offset:
#include <fstream>
#include <iostream>
using namespace std ;
int main ( )
{
fstream strm ;
strm. open ( "doc1.txt" , ios_base :: in ) ;
if ( ! strm. is_open ( ) ) {
cout << "Open file failed" << endl ;
return 1 ;
}
char c ;
strm. seekg ( 27 ) ;
strm. seekg ( 0 , ios_base :: cur ) ;
strm. get ( c ) ;
cout << c << endl ;
strm. seekg ( — 5 , ios_base :: cur ) ;
strm. get ( c ) ;
cout << c << endl ;
strm. seekg ( + 10 , ios_base :: cur ) ;
strm. get ( c ) ;
The get() member function shifts the pointer one place ahead after its execution.
The equivalent function for outputting is:
Note the “p” in seekp for put, as opposed to “g” in seekg for get.
Conclusion
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. To append text to the file, the stream has to be opened for appending. Make a habit of always closing the stream after it has been opened and used. If the file is an image file, then ios_base::binary will have to be ORed using | , with the second argument of the open() member function. This article hopefully assisted you in using the C++ fstream.
Include fstream c что это
Для работы с файлами в стандартной библиотеке определен заголовочный файл fstream , который определяет базовые типы для чтения и записи файлов. В частности, это:
ifstream : для чтения с файла
ofstream : для записи в файл
fstream : совмещает запись и чтение
Для работы с данными типа wchar_t для этих потоков определены двойники:
Открытие файла
При операциях с файлом вначале необходимо открыть файл с помощью функции open() . Данная функция имеет две версии:
Для открытия файла в функцию необходимо передать путь к файлу в виде строки. И также можно указать режим открытия. Список доступных режимов открытия файла:
ios::in : файл открывается для ввода (чтения). Может быть установлен только для объекта ifstream или fstream
ios::out : файл открывается для вывода (записи). При этом старые данные удаляются. Может быть установлен только для объекта ofstream или fstream
ios::app : файл открывается для дозаписи. Старые данные не удаляются.
ios::ate : после открытия файла перемещает указатель в конец файла
ios::trunc : файл усекается при открытии. Может быть установлен, если также установлен режим out
ios::binary : файл открывается в бинарном режиме
Если при открытии режим не указан, то по умолчанию для объектов ofstream применяется режим ios::out , а для объектов ifstream — режим ios::in . Для объектов fstream совмещаются режимы ios::out и ios::in .
Однако в принципе необязательно использовать функцию open для открытия файла. В качестве альтернативы можно также использовать конструктор объектов-потоков и передавать в них путь к файлу и режим открытия:
При вызове конструктора, в который передан путь к файлу, данный файл будет автоматически открываться:
Вообще использование конструкторов для открытия потока является более предпочтительным, так как определение переменной, представляющей файловой поток, уже преполагает, что этот поток будет открыт для чтения или записи. А использование конструктора избавит от ситуации, когда мы забудем открыть поток, но при этом начнем его использовать.
В процессе работы мы можем проверить, окрыт ли файл с помощью функции is_open() . Если файл открыт, то она возвращает true:
Закрытие файла
После завершения работы с файлом его следует закрыть с помощью функции close() . Также стоит отметить, то при выходе объекта потока из области видимости, он удаляется, и у него автоматически вызывается функция close.
Стоит отметить, что при компиляции через g++ следует использовать флаг -static , если программа работает со файлами и использует типы из заголовочного файла fstream: