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

Ios trunc c что это

  • автор:

Ios trunc c что это

There may be times when you want to modify the way a file is opened or used in a program. For example, in some cases it is desirable that writes append to the end of a file rather than overwriting the existing values. The file stream constructor takes a second argument, the open mode , that allows such variations to be specified. Here is an example that creates a file stream object Str , connects it to the external file named «inout.txt» , and opens it for reading and for writing at the end of the file:

Note that if the «inout.txt» file doesn’t exist it will be created.

30.3.1 The Open Mode Flags

The open mode argument is of type std::ios_base::openmode , which is a bitmask type like the format flags and the stream state. Table 32 defines the following bits:

Open file for reading

Open file for writing

Start position is at file end

Append file; that is, always write to the end of the file

Truncate file; that is, delete file content

30.3.1.1 The in and out Open Modes

Input (and output) file streams always have the in (or out ) open mode flag set implicitly. An output file stream, for instance, knows that it is in output mode and you need not set the output mode explicitly. Instead of writing:

you can simply say:

Bidirectional file streams, on the other hand, do not have the flag set implicitly. This is because a bidirectional stream does not have to be in both input and output mode in all cases. You might want to open a bidirectional stream for reading only or writing only. Bidirectional file streams therefore have no implicit input or output mode. You must always set a bidirectional file stream’s open mode explicitly.

30.3.1.2 The Open modes ate, app, and trunc

Each file maintains a single file position that indicates the position in the file where the next byte will be read or written. When a file is opened, the initial file position is usually at the beginning of the file. The open modes std::ios_base::ate (meaning at end ) and std::ios_base::app (meaning append ) change this default to the end of the file.

There is a subtle difference between ate and app mode. If the file is opened in append mode, all output to the file is done at the current end of the file, regardless of intervening repositioning. Even if you modify the file position to a position before the file’s end, you cannot write there. With ate mode, you can navigate to a position before the end of file and write to it.

If you open an already existing file for writing, you usually want to overwrite the content of the output file. The open mode std::ios_base::trunc (meaning truncate ) has the effect of discarding the file content, in which case the initial file length is set to 0 . Therefore, if you want to replace a file’s content rather than extend the file, you must open the file in std::ios_base::out | std::ios_base::trunc . Note that the file position is at the beginning of the file in this case, which is exactly what you expect for overwriting an output file.

If you want to extend an output file, you open it with the bitwise or of std::ios_base::ate and std::ios_base::app mode. In this case, the file content is retained because the trunc flag is not set, and the initial file position is at the file’s end. However, you may additionally set the trunc flag; the file content is discarded and the output is done at the end of an empty file.

Input mode only works for files that already exist. Otherwise, the stream construction fails, as indicated by failbit set in the stream state. Files that are opened for writing are created if they do not yet exist. The constructor only fails if the file cannot be created.

30.3.1.3 The binary Open Mode

The std::ios_base::binary open mode is discussed in Section 30.4.

30.3.2 Combining Open Modes

The effect of combining these open modes is similar to the mode argument of the C library function fopen(name,mode) . Table 33 gives an overview of all permitted combinations of open modes for text files and their counterparts in C stdio. Combinations of modes that are not listed in the table (such as both trunc and app ) are invalid, and the attempted open() operation fails.

Flag Names Effects

Open text file for reading only

Truncate to 0 length, if existent, or create text file for writing only

Append; open or create text file only for writing at end of file

Open text file for update (reading and writing)

Truncate to 0 length, if existent, or create text file for update

Append; open or create text file for update, writing at end of file

30.3.3 Default Open Modes

The open mode parameter in constructors and open() functions of file stream classes have a default value. The default open modes are listed in Table 34.

# File I/O

C++ file I/O is done via streams. The key abstractions are:

std::istream for reading text.

std::ostream for writing text.

std::streambuf for reading or writing characters.

Formatted input uses operator>> .

Formatted output uses operator<< .

Streams use std::locale , e.g., for details of the formatting and for translation between external encodings and the internal encoding.

More on streams: Library

# Writing to a file

There are several ways to write to a file. The easiest way is to use an output file stream ( ofstream ) together with the stream insertion operator ( << ):

Instead of << , you can also use the output file stream’s member function write() :

After writing to a stream, you should always check if error state flag badbit has been set, as it indicates whether the operation failed or not. This can be done by calling the output file stream’s member function bad() :

# Opening a file

Opening a file is done in the same way for all 3 file streams ( ifstream , ofstream , and fstream ).

You can open the file directly in the constructor:

Alternatively, you can use the file stream’s member function open() :

You should always check if a file has been opened successfully (even when writing). Failures can include: the file doesn’t exist, file hasn’t the right access rights, file is already in use, disk errors occurred, drive disconnected . Checking can be done as follows:

When file path contains backslashes (for example, on Windows system) you should properly escape them:

or use raw literal:

or use forward slashes instead:

If you want to open file with non-ASCII characters in path on Windows currently you can use non-standard wide character path argument:

# Reading from a file

There are several ways to read data from a file.

If you know how the data is formatted, you can use the stream extraction operator ( >> ). Let’s assume you have a file named foo.txt which contains the following data:

Then you can use the following code to read that data from the file:

The stream extraction operator >> extracts every character and stops if it finds a character that can’t be stored or if it is a special character:

  • For string types, the operator stops at a whitespace («) or at a newline ( \n ).
  • For numbers, the operator stops at a non-number character.

This means that the following version of the file foo.txt will also be successfully read by the previous code:

The stream extraction operator >> always returns the stream given to it. Therefore, multiple operators can be chained together in order to read data consecutively. However, a stream can also be used as a Boolean expression (as shown in the while loop in the previous code). This is because the stream classes have a conversion operator for the type bool . This bool() operator will return true as long as the stream has no errors. If a stream goes into an error state (for example, because no more data can be extracted), then the bool() operator will return false . Therefore, the while loop in the previous code will be exited after the input file has been read to its end.

If you wish to read an entire file as a string, you may use the following code:

This code reserves space for the string in order to cut down on unneeded memory allocations.

If you want to read a file line by line, you can use the function getline()

If you want to read a fixed number of characters, you can use the stream’s member function read() :

After executing a read command, you should always check if the error state flag failbit has been set, as it indicates whether the operation failed or not. This can be done by calling the file stream’s member function fail() :

# Opening modes

When creating a file stream, you can specify an opening mode. An opening mode is basically a setting to control how the stream opens the file.

(All modes can be found in the std::ios namespace.)

An opening mode can be provided as second parameter to the constructor of a file stream or to its open() member function:

It is to be noted that you have to set ios::in or ios::out if you want to set other flags as they are not implicitly set by the iostream members although they have a correct default value.

If you don’t specify an opening mode, then the following default modes are used:

  • ifstream — in
  • ofstream — out
  • fstream — in and out

The file opening modes that you may specify by design are:

Open Mode C stdio Equivalent Effect
Mode Meaning For Description
app append Output Appends data at the end of the file.
binary binary Input/Output Input and output is done in binary.
in input Input Opens the file for reading.
out output Output Opens the file for writing.
trunc truncate Input/Output Removes contents of the file when opening.
ate at end Input Goes to the end of the file when opening.

Note: Setting the binary mode lets the data be read/written exactly as-is; not setting it enables the translation of the newline ‘\n’ character to/from a platform specific end of line sequence.

For example on Windows the end of line sequence is CRLF ( "\r\n" ).
Write: "\n" => "\r\n"
Read: "\r\n" => "\n"

What is the difference among ios::app, out, and trunc in c++?

I know that the default file open mode is out. And I think out will overwrite the data in the file, but in the following code, it age data doesn’t overwrite name data.

Then I’m confused about the three open mode for file – app, out, trunc.

If for name I enter “Zara” and age “9”, the output should be “9ara”. However, it is not. It is “Zara 9”.

2 Answers 2

ios::out is the default mode for std::ofstream , it means that output operations can be used (i.e. you can write to the file).

ios::app (short for append) means that instead of overwriting the file from the beginning, all output operations are done at the end of the file. This is only meaningful if the file is also open for output.

ios::trunc (short for truncate) means that when the file is opened, the old contents are immediately removed. Again, this is only meaningful if the file is also open for output.

Your code just uses the default ios::out mode. So it starts writing from the beginning of the file, but doesn’t remove the old contents. So the new contents will overlay what’s already there — if the file is originally 10 bytes long, and you write 3 bytes, the result will be the 3 bytes you write followed by the remaining 7 bytes of the original contents. More concretely, if the file originally contains:

and you write FN LN and then 20 (with newlines after each), the resulting file will look like:

because you only overwrite the first 9 bytes of the file (assuming Unix-style newlines).

C++. Файловая система C++. Общие принципы работы. Примеры. Открытие/закрытие файла

Файловая система C++. Общие принципы работы. Примеры. Открытие/закрытие файла

Содержание

  • 1. Подключение доступа к классам организации работы с файловой системой C++
  • 2. Создание файлового потока. Каким образом осуществляется связь потока с файлом? Функция open()
  • 3. Способы открытия файла. Функция openmode()
  • 4. Функция is_open() . Проверка открытия файла. Пример
  • 5. Функция close() . Закрытие файла. Пример
  • 6. Примеры открытия/закрытия файла функцией open() . Проверка открытия файла функцией is_open()

Поиск на других ресурсах:

1. Подключение доступа к классам организации работы с файловой системой C++

Файловый ввод/вывод есть частью общей системы ввода/вывода языка C++. Для того, чтобы в программе можно было использовать файловый ввод/вывод предварительно должен быть подключен модуль fstream

В этом модуле реализованы основные классы для работы с файловой системой:

  • ifstream – используется для организации ввода из файлового потока;
  • ofstream – используется для организации вывода в файл (файловый поток);
  • fstream – используется для обеспечения ввода/вывода.
2. Создание файлового потока. Каким образом осуществляется связь потока с файлом? Функция open()

Чтобы создать файловый поток нужно объявить экземпляр одного из классов ifstream , ofstream или fstream

Созданный поток связывается с файлом с помощью функции open() , которая имеет различные реализации в разных классах.

В классе ifstream функция open() имеет следующий прототип

  • filename – имя открываемого файла. Имя может быть полным или сокращенным, например, «myfile.txt» ;
  • mode – способ открытия файла. Этот параметр принимает значение ios::in , которое описывается в функции openmode() . Значение ios::in означает, что файл открывается только для ввода.

В классе ofstream функция open() имеет следующий прототип

  • filename – имя открываемого файла;
  • mode – параметр, который задает способ открытия файла. В этом параметре значение ios::out означает, что файл открывается для вывода. Значение ios::trunc означает, что предшествующее содержимое существующего файла с таким самым именем будет удалено, а длина файла станет равной нулю.

В классе fstream прототип функции open() следующий

  • filename – имя файла;
  • mode – параметр, который задает способ открытия файла. Как видно из значения параметра mode , файл открывается и для записи и для чтения.
3. Способы открытия файла. Функция openmode()

Способы открытия файла могут быть разными. Значения, которые описывают способы открытия файла, реализованы в функции openmode() . Ниже приведены значения, которые могут возвращаться функцией openmode() и объяснение к ним:

  • ios::app – записываемые данные дописываются в конец файла;
  • ios::ate – при открытии файла происходит поиск конца файла. Но запись в файл может осуществляться в любое место этого файла;
  • ios::binary – позволяет открыть файл в бинарном (двоичном) режиме. Существует два режима открытия файла: текстовый и бинарный. По умолчанию файлы открываются в текстовом режиме;
  • ios::in – файл открывается для ввода (происходит чтение из файла);
  • ios::out – файл открывается для вывода (происходит запись в файл);
  • ios::trunc – означает, что предыдущее содержимое существующего файла с таким самым именем будет удалено, а длина файла станет равной нулю. Если открыть поток вывода с помощью класса ofstream все содержимое файла с тем же именем стирается.

Способы открытия файла можно комбинировать между собою с помощью операции | (побитовое ИЛИ).

Пример. Способы открытия файла.

4. Функция is_open() . Проверка открытия файла. Пример

Функция is_open() предназначена для проверки, закрыт ли файл или нет. Эта функция реализована в классах ifstream , ofstream и fstream .

Функция имеет следующий прототип:

Функция возвращает true , если поток связан с открытым файлом. В другом случае функция возвращает false .

Пример. Демонстрируется определение открытия файла для объекта os класса ofstream . Если файл открыт, то этот файл закрывается.

5. Функция close() . Закрытие файла. Пример

Чтобы закрыть файл, нужно вызвать функцию close() .

Например. Далее продемонстрировано открытие и закрытие файла для потока ifstream

6. Примеры открытия/закрытия файла функцией open() . Проверка открытия файла функцией is_open()

Открыть файл можно одним из двух способов:

  • с помощью функции open() ;
  • с помощью конструктора класса (см. примеры ниже).

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

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

  • с помощью соответствующей проверки оператором условного перехода if ;
  • с помощью функции is_open() .

Пример 1. Открытие файла для вывода (записи).

Пример 2. Открытие файла для ввода (чтения)

Пример 3. Открытие файла для вывода (записи). Использование функции is_open() .

Пример 4. Открытие файла для ввода (чтения). Использование функции is_open() .

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

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