class ofstream
Back class ifstream, which we reviewed earlier, and is designed to write to a file.
As in ifstream, to open or create a file using a constructor or method open().
1 2 3 4 5 6 7 | ofstream fileo; // Создаем файл fileo.open("d:\\1\\Результат.txt"); // Открываем для дописывания fileo.open("d:\\1\\Результат.txt"/*,ios_base::app*/); |
or designer:
1 2 3 4 5 | // Создаем файл ofstream fileo("d:\\1\\Результат.txt"); // Открываем для дописывания ofstream fileo("d:\\1\\Результат.txt",ios_base::app); |
Parameter ios_base::app indicated, if you want to append to the end of an existing file. For example when the program keeps a log of their work
For checking a file open meets all the same is_open()
1 2 3 4 5 6 | if( fileo.is_open() ) cout << "Файл создан" << endl; else { cout << "Файл не создан"; cin.get(); return -1; } |
The principle is the same. You can check whether a file is opened, using inlogical expression very variable file:
1 | if ( !fileo ) cout << "Файл НЕ создан" << endl; |
Statement <<
Forwards the formatted output to a file. The principle is the same, that of the analog in iostream.
1 2 3 4 5 6 | // Запись строкой string s = "Привет мир"; // Вещественное double d = 123.456; fileo << s << endl << d << endl; |
It is intended to be displayed in text files. Controlled formatting operations such as width() or setf(). Their counterparts are fully methods of the same name iostream.
The sequence of output variables as indicated from left to right: The first variable will be output, listed closest to fillet, then following it.
operator endl
Similarly, the operator of iostream manufactures transfer record of the carriage to a new line in a text file.
method write
It used in binary files for writing the memory block (byte array) in the file as they are. Any variable is also a array bytes, rather it can be seen as. Accordingly, this method writes to the file its machine representation (the kind of the way it looks in the memory).
1 2 3 4 5 6 7 8 9 10 11 12 | // Запись побайтно // Строки char *sc = "И еще раз\n"; fileo.write(sc,strlen(sc)); // Целого в машинном представлении int k = 123; fileo.write((char*)&k,sizeof(k)); // Вещественного в машинном представлении double dd = 456.789; fileo.write((char*)&dd,sizeof(dd)); |
This method takes two parameters: Pointer to a block of data and the number of bytes, that this unit takes. In the example, the string takes strlen() bytes, whole sizeof() (which will give 4 32-bit integer and for OSes 8 for real).
Once again I should emphasize the, that unlike the formatted output operator <<, method write() It does not display data in text form.
method close
Closes file method close(). for files, writable, as opposed to reading files, closing a file – mandatory ritual. Unclosed file can not obtain the data. This effect can occur due to the buffering itself OSes, when data, discharged into the file, They are stored in fact in mind and just do not come to a file. The operating system itself decides, when the data is time to merge.
Such “deferred” plums called “commit” (from the Latin commit). By the way this effect very well use a database management system, where to insert records fall into the storage memory (called transaction). It was only after a special command en masse written to the database file itself. Method close() just an example of a team closing a transaction with the file.
It is worth mentioning just in case, that if you want to commit to produce data without closing the file itself, you need to use the method flush()
1 | fileo.flush(); |
These deposits will go on the record in the file, but it will still be open for entries. This method is not often used, but useful to know about it.
width formatting methods, precision
As in iostream, for the beautiful layout of data in data formatting file can be used to display operator << .
width() indicates the width in characters, which will be laid in the displayed value, and precision() the number of digits of the fractional part of a real. The simplest example: output table to a text file the values of the trigonometric functions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // Форматирование вывода double d = 1; int i; for ( i = 0; i < 10; i++ ){ d += sin(i/d); // Указываем ширину ячейки для целого и выводим целое fileo.width(20); // Выводим целое fileo << i; // Указываем ширину ячейки для вещественного и // кол-во знаков после запятой максимум fileo.width(20); fileo.precision(5); // выводим вещественное fileo << d; // Переводим каретку на новую строку fileo<<endl; } |
positioning methods seekp, tellp
To move a file as in the case of ifstream There is a function of the position of the permutation. it is called seekp() and receives the same parameters as described above for seekg().
To get the current position of a similar feature in bytes from the beginning of the file tellp().
Videos about working with files in C ++:
aaaaaa
bdncv mxjnckjndjkdnl;g;,.,mvjkbr
Артём за первым компом за тобой уже выехали-_-
andrey privet andrey privet
andrey privet
Нелезь Артём оно тебя сажрёт сажрёт сажрёт сажрёт сажрёт сажрёт сажрёт сажрёт сажрёт сажрёт сажрёт сажрёт сажрёт сажрёт
andrey ti vobla
пРИВИТ АРТЁМ!!!!