Ios binary c что это
Перейти к содержимому

Ios binary c что это

  • автор:

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 work with binary files in C++?

Zekumoru Dragonhart

There two types of files: Binary and Text.

A text file is basically a binary file, though, made to work with characters and symbols while a binary file is made to work with… well, binaries.

It is much easier to read text files because we understand them. Binary files are not however because we humans are not computers that understand sequences of 0s and 1s.

For convention, to view binary files, we use hex values. Here’s an example below that shows our file sample.txt in text form:

And in binary form:

Binary Operations

To create a binary file, we create an fstream object then pass as parameters the name of the file we want to create and the modes on how we want to work with file.

In the code above, we create an fstream object with the name sample.bin , where bin stands for binary, then we specify what actions we want to do with this file.

ios::in means that we’ll be handling input to this file such as writing data.

ios::out means that we’ll be taking or reading the contents of this file.

ios::binary means that we specifically tell that we’ll be working with binaries, why? Because, by default, fstream object works with text.

ios::trunc means that we want this file to be empty, if the file sample.bin already exists, ios::trunc will discard everything inside the file. You can think of ios::trunc like the clear() function of a string object.

You probably know this but after creating our file, we would want to check if it is open or not and also close it after we’re done with it:

Now that we have our file opened, how do we put/write something to it? We can use the put() function to put one character at a time or use the write() function to write a block of data.

Here’s an example on how to use the put() function:

Running that line of code will give us a file called sample.bin and inside we’ll see a .

How about if we want to write a chunk of data?

Here, we created an array of characters with size of 20 and put inside the string Hello world! then we wrote it in the file using the write() function. First parameter is technically (if you know about pointers then you’ll understand) the address of the first element in the array. Second parameter is the size of the array, and it is 20 .

How about reading data? Easy, just use get() to get/take one character from the file or use read() to read a block of data. They are pretty much similar to put() and write() but instead of passing the data to write, we’re passing the variable where we want to put the data being read.

Now that we know how to read and write, let me introduce to seeking and telling our current position in the file. Just as we have a cursor telling us where we are in a our document, article or text when we’re writing to it. We also have a cursor in the file stream.

There are 4 functions to accomplish this task:

seekp(x) moves our put/reading cursor by x. It can be negative.

tellp() tells the current position of our reading cursor.

seekg(x) moves our get/writing cursor by x. It can be negative.

tellg() tells the current position of our writing cursor.

Difference between the p and g parts is that we use p when we’re doing output/reading operations while g is for input/writing operations of the file.

seekp() and seekg() also have a second parameter that we can give to tell our cursor to move/seek from the beginning, end or current position. They accept as second parameter these values: ios_base::beg (seek from the beginning), ios_base::end (seek from the end) and ios_base::cur (seek from the current position).

I have been ditching examples and that’s not good. Here’s an example how the functions above work:

You might be wondering: what’s with that \0 ? That’s called null or nothing. That’s the default value of a character. Our Hello world! string has 12 characters and it doesn’t fill everything in our character array, hence, the remaining unused characters are in their default value or null .

Binary files don’t ignore newlines, nulls, etc. unlike text files. They put them inside binary files. This is both a good thing and a bad thing. A bad thing because what if we want to write a dynamic array such as a string in our binary file? We will need to also specify its size before we perform any writing. We can’t just simply use null to denote our end of string, it doesn’t make sense because we might have been using it as well for other things.

Saving An Object Of Struct

Good thing about binaries is that we can save objects of a structure or a class. For example, we have a structure called person :

And we want to save its data into our file. We can use the write() function to do so, how? Take a look at the code below:

First, we created our person object called p . Then, we assigned its values. Finally, we wrote that p object into our binary file. If we try to open our binary file, we will receive strange symbols. In this case, it’s better to use hex values to view this file. And it should look like this:

You can tell that the first 30 bytes is our string Some Name . After them we have these two CC hex values then the 4 bytes 0A 00 00 00 . Those last 4 bytes are in little-endian format, if we try to convert it to big-endian, we’ll have 00 00 00 0A and that’s our integer! Why 4 bytes though? Most systems use 4 bytes on integers. That A in the end is 10 in decimal and that’s our number!

Using binary files also reduces space, how so? If we had to save a number into a text file, let’s say for example the number 10, it will be recognized as two separate characters 1 and 0 . And that would be 31 30 in binary where we could simply use 0A . This example is cheap, you might be probably thinking, integer is 4 bytes. Well, think if we used the number 2849294 , that is 7 bytes! But with binaries, it’s simply: 0E 7A 2B 00 or 4 bytes.

The (char*)& dilemma

If you recall, the write() and read() function accepts as first parameter a character pointer. In other words, it accepts an address. And from that address, it performs operations until the specified size.

Why does it accept a character pointer? Because a char is one byte. We want to work with bytes byte-by-byte hence we use char .

To fully understand the concept why we used (char*)& p as the first parameter in the code above. You need to learn about pointers. They are crucial if you really want to understand. Though, I’ll try to explain it as briefly and simpler as possible.

Have you ever tried doing something similar to this: int* pnum = (int*)& num; ? num here is a int variable with the value of 14 . First, we took the address of num and then we dereferenced it, it seems stupid because pointing to something and dereferencing it will give us the value of num or 14 . However, we are not doing this to play around with 14 but to get its value in hex form. Yes, we’re getting its value in the form of hex! Pretty cool I should say. This should also explain why we got the 4 bytes in our integer earlier (the 0A 00 00 00 one).

Why did I explain this now? With clear example from int* , we should be able now to fully grasp char* .

One thing to note: even though you see char , we’re not actually working with characters, we’re working with bytes! Remember, we are working with bytes!

Now that you understand the concept behind (int*)& var , I reckon you already understand now why we used (char*)& var .

If not, well… Here one more explanation:

In the code: file.write((char*)& p, sizeof(person)); , we can think of the object p as an array that contains both a char array, or name, and an int, or age . As an array, we know that its first element is the main address of the array. Now, we want to write this array into our binary file using write() until the specified size. It’s easy to look up its size, we just have to use the function sizeof() !

With this, it will write down the content of our structure p into our binary file byte-by-byte or char-by-char until it reaches the specified size.

Reading Our Binary File

Now that we have saved the contents of our p object. It might be better if we could read it back and assign its values into a new person object!

The procedure is the same but now we use read() instead of write() :

See? Same procedure.

And what’s cool about binary files is this:

If a binary file’s structure is not known, its contents are inaccessible or illegible.

And that means: security. Not really secured as of some data can be interpreted by simple text editors because they correspond into an ASCII code. However, how the data is organized is going to be unknown and that’s a good thing for our security.

Conclusion

We talked about what binary files are, how to create one and manipulate it using seekg() , seekp() , tellg() , tellp() , put() , get() , write() and read() .

We also talked the advantages of binary files such as space and security. And why to write our objects into our binary files.

Each file you see is, in fact, a binary file. Make it be mp3, mp4, or even exe files.

Whew… I wrote this article for hours and still not enough to fully explain things but I hope I skimmed you through every basics you’ll need to understand binary files.

I actually hated binary files because I thought they were too complex to comprehend. However, it’s funny and simple how they work just as Leonardo da Vinci said Simplicity is the ultimate sophistication . I still don’t know if some of my explanations are wrong and if so, please correct me. I’m actually a self-taught programmer and I have been programming for 2 years at home. Learning stuff here and there.

I might edit this article in the future, I feel like some things are left unexplained or explained ambiguously.

Anyway, I hope I clarified some things and made binary files less intimidating. Happy coding!

What's the difference between opening a file with ios::binary or ios::out or both?

I’m trying to figure out the difference between opening a file like:

I found that all of these forms are identical: in all cases, the same output on the file is produced using either *fileName*<< or *fileName*.write() .

Jamal's user avatar

2 Answers 2

ios::out opens the file for writing.

ios::binary makes sure the data is read or written without translating new line characters to and from \r\n on the fly. In other words, exactly what you give the stream is exactly what’s written.

C++
Файловый ввод-вывод

C ++-файл ввода-вывода выполняется через потоки . Ключевыми абстракциями являются:

std::istream для чтения текста.

std::ostream для std::ostream текста.

std::streambuf для чтения или записи символов.

В форматированном вводе используется operator>> .

Форматированный вывод использует operator<< .

В потоках используется std::locale , например, для подробностей форматирования и для перевода между внешними кодировками и внутренней кодировкой.

Открытие файла

Открытие файла выполняется одинаково для всех 3 потоков файлов ( ifstream , ofstream и fstream ).

Вы можете открыть файл непосредственно в конструкторе:

Кроме того, вы можете использовать функцию члена потока файлов open() :

Вы всегда должны проверить, был ли файл успешно открыт (даже при написании). Ошибки могут включать: файл не существует, файл не имеет прав доступа, файл уже используется, произошли ошибки диска, отключен диск . Проверка может быть выполнена следующим образом:

Когда путь к файлу содержит обратную косую черту (например, в системе Windows), вы должны правильно их избежать:

или использовать исходный литерал:

или вместо этого используйте косые черты:

Если вы хотите открыть файл с не-ASCII-символами в пути в Windows, в настоящее время вы можете использовать нестандартный аргумент пути к широкому символу:

Чтение из файла

Существует несколько способов чтения данных из файла.

Если вы знаете, как форматируются данные, вы можете использовать оператор извлечения потока ( >> ). Предположим, у вас есть файл с именем foo.txt, который содержит следующие данные:

Затем вы можете использовать следующий код для чтения этих данных из файла:

Оператор извлечения потока >> извлекает каждый символ и останавливается, если он находит символ, который нельзя сохранить, или если он является особым символом:

  • Для типов строк оператор останавливается в пробеле ( ) или в новой строке ( \n ).
  • Для чисел оператор останавливается с символом, отличным от числа.

Это означает, что следующая версия файла foo.txt также будет успешно прочитана предыдущим кодом:

Оператор извлечения потока >> всегда возвращает переданный ему поток. Поэтому несколько операторов могут быть соединены друг с другом, чтобы читать данные последовательно. Тем не менее, поток также может быть использован в качестве логического выражения (как показано в while петли в предыдущем коде). Это связано с тем, что классы потоков имеют оператор преобразования для типа bool . Этот оператор bool() вернет true пока поток не имеет ошибок. Если поток переходит в состояние ошибки (например, поскольку больше не может быть извлечено данных), то оператор bool() вернет false . Таким образом, в while цикл в предыдущем коде будет после того, как вышел из входного файла был прочитан до конца.

Если вы хотите прочитать весь файл в виде строки, вы можете использовать следующий код:

Этот код резервирует пространство для string , чтобы сократить ненужные распределения памяти.

Если вы хотите прочитать файл по строкам, вы можете использовать функцию getline() :

Если вы хотите прочитать фиксированное количество символов, вы можете использовать функцию члена потока read() :

После выполнения команды чтения, вы всегда должны проверить , если состояние ошибки флаг failbit был установлен, поскольку он указывает на то удалось ли операция или нет. Это можно сделать, вызвав функцию члена файлового потока fail() :

Запись в файл

Существует несколько способов записи в файл. Самый простой способ — использовать поток выходных файлов ( ofstream ) вместе с оператором вставки потока ( << ):

Вместо « << вы также можете использовать функцию члена потока выходного файла write() :

После записи в поток, вы всегда должны проверить , если состояние ошибки флаг badbit был установлен, поскольку он указывает на то удалось ли операция или нет. Это можно сделать, вызвав функцию члена потока выходного файла bad() :

Режимы открытия

При создании потока файлов вы можете указать режим открытия. Режим открытия — это, в основном, параметр для управления тем, как поток открывает файл.

(Все режимы можно найти в пространстве имен std::ios .)

Режим открытия может быть предоставлен в качестве второго параметра конструктору файлового потока или его функции open() :

Следует отметить, что вам нужно установить ios::in или ios::out если вы хотите установить другие флаги, поскольку они неявно устанавливаются членами iostream, хотя они имеют правильное значение по умолчанию.

Если вы не укажете режим открытия, используются следующие режимы по умолчанию:

  • ifstream — in
  • ofstream — out
  • fstream — in и out

Режимы открытия файла, которые вы можете указать по дизайну:

Режим Имея в виду За Описание
app присоединять Выход Добавляет данные в конец файла.
binary двоичный Ввод, вывод Вход и выход выполняются в двоичном формате.
in вход вход Открывает файл для чтения.
out выход Выход Открывает файл для записи.
trunc усекать Ввод, вывод Удаляет содержимое файла при открытии.
ate в конце вход Открывается до конца файла.

Примечание. Установка binary режима позволяет считывать / записывать данные в точности как есть; не устанавливая его, это позволяет переносить символ новой строки '\n' / \ на определенный конец строки последовательности.

Закрытие файла

Явное закрытие файла редко необходимо в C ++, так как поток файлов автоматически закрывает связанный файл в своем деструкторе. Тем не менее, вы должны попытаться ограничить время жизни объекта потока файлов, чтобы он не закрывал дескриптор файла дольше, чем необходимо. Например, это можно сделать, поместив все операции с файлами в собственную область ( <> ):

Вызов close() явно необходимо , только если вы хотите использовать один и тот же fstream объект позже, но не хотите , чтобы сохранить файл открыть между ними:

Промывка потока

Потоки файлов по умолчанию буферизуются, как и многие другие типы потоков. Это означает, что запись в поток не может привести к немедленному изменению базового файла. Чтобы заставить все буферизованные записи совершать сразу, вы можете очистить поток. Вы можете сделать это напрямую, вызывая метод flush() или с помощью манипулятора std::flush stream:

Существует поток манипулятор std::endl который объединяет запись новой строки с потоком потока:

Буферизация может улучшить производительность записи в поток. Поэтому приложения, выполняющие много писем, должны избегать излишней очистки. Напротив, если операции ввода-вывода выполняются нечасто, приложения должны часто промывать, чтобы избежать застревания данных в объекте потока.

Чтение файла ASCII в строку std ::

Метод rdbuf() возвращает указатель на streambuf который может быть streambuf в buffer через stringstream::operator<< member.

Другая возможность (популяризированная в Effective STL от Scott Meyers ):

Это хорошо, потому что требует небольшого кода (и позволяет читать файл непосредственно в любом контейнере STL, а не только в строках), но может быть медленным для больших файлов.

ПРИМЕЧАНИЕ . Дополнительные скобки вокруг первого аргумента конструктору строк необходимы для предотвращения наиболее неприятной проблемы синтаксического анализа .

Последний, но тем не менее важный:

что, вероятно, является самым быстрым вариантом (из трех предложенных).

Чтение файла в контейнер

В приведенном ниже примере мы используем std::string и operator>> для чтения элементов из файла.

В приведенном выше примере мы просто итерации через файл, читающий один «элемент» за раз, используя operator>> . Этот же std::istream_iterator может быть достигнут с помощью std::istream_iterator который является итератором ввода, который считывает один «элемент» за раз из потока. Также большинство контейнеров можно построить с использованием двух итераторов, чтобы мы могли упростить приведенный выше код:

Мы можем расширить это, чтобы прочитать любые типы объектов, которые нам нравятся, просто указав объект, который мы хотим прочитать как параметр шаблона, для std::istream_iterator . Таким образом, мы можем просто расширить сказанное выше, чтобы читать строки (а не слова) следующим образом:

Чтение `struct` из форматированного текстового файла.

file4.txt

Выход:

Копирование файла

С C ++ 17 стандартным способом копирования файла является заголовок <filesystem> и использование copy_file :

Библиотека файловой системы была первоначально разработана как boost.filesystem и, наконец, объединена с ISO C ++ с C ++ 17.

Проверка конца файла внутри условия цикла, неправильная практика?

eof возвращает true только после чтения конца файла. Он НЕ указывает, что следующее чтение будет концом потока.

Вы можете правильно написать:

проще и меньше подверженности ошибкам.

  • std::ws : отбрасывает ведущие пробелы из входного потока
  • std::basic_ios::fail : возвращает true если произошла ошибка в связанном потоке

Запись файлов с нестандартными языковыми настройками

Если вам нужно записать файл с использованием разных настроек языкового стандарта по умолчанию, вы можете использовать std::locale и std::basic_ios::imbue() чтобы сделать это для определенного потока файлов:

Руководство для использования:

  • Перед открытием файла вы всегда должны применять локальный поток.
  • Как только поток будет пропитан, вы не должны изменять языковой стандарт.

Причины ограничений: при создании файлового потока с локалью имеет неопределенное поведение, если текущая локаль не является независимой от состояния или не указывает на начало файла.

Потоки UTF-8 (и другие) не являются независимыми от состояния. Также поток файлов с локалью UTF-8 может попробовать и прочитать маркер спецификации из файла при его открытии; поэтому просто открытие файла может читать символы из файла, и оно не будет в начале.

Явное переключение на классический язык «C» полезно, если ваша программа использует другой стандарт по умолчанию, и вы хотите обеспечить фиксированный стандарт для чтения и записи файлов. С предпочтительной локалью «C» пример записывает

Если, например, предпочтительный языковой стандарт является немецким и, следовательно, использует другой формат чисел, пример записывает

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *