header fstream It provides the functionality to read data from a file and write to the file. In general, it is very similar to the header iostream, who works with the console, because the console is also a file. Therefore, all the basic operations are the same, for small differences, as in the previous topic on iostream.
The most frequent operations following:
- Operators Redirection O – << and >>
- Methods of recording and reading rows getline() and get() c put()
- Streaming read and write methods write() and read()
- Public method creation and closing files open() and close()
- The methods of verification whether the file is opened is_open() and whether the file end is reached eof()
- Setting the formatted output for >> through width() and precision()
- positioning operation tellg(), tellp() and seekg(), seekp()
It's not all possibilities, which provides library fstream. Consider all now we do not, since their range of application is narrow enough. Acquainted with the above. Start by reading the class.
class ifstream
It provides opportunities to read files. Open the file in two ways: calling method open() or by entering the path to it in the constructor. You need to prepare a text file, before, start typing the code. On the disc d, create a folder named 1 and in it, create a file with the extension txt – “файл.txt”.
1 2 3 4 5 6 7 8 9 | #include <iostream> #include <fstream> // подключаем библиотеку using namespace std; int main() { ifstream file; // создаем объект класса ifstream file.open("d:\\1\\файл.txt"); // открываем файл } |
Opening a file in the constructor looks like this:
1 2 3 4 5 6 7 8 | #include <iostream> #include <fstream> // подключаем библиотеку using namespace std; int main() { ifstream file ("d:\\1\\файл.txt"); // открываем файл в конструкторе } |
So we ask to open a file named file.txt txt, which is in the folder with the name 1, and the folder is on drive d.
Using the open method() conveniently, if the programmer does not want to be tied directly to a file. Suddenly you need a class property or global variable, well, then open the file already. If you need to open a file within a certain function, to work with him and to close, you can set the path to the file directly in the constructor. In general, depending on the situation.
opening file, desirable to prescribe by: if he opened? Since there are a number of reasons, on which the file can not be opened, and we do not see. For example, file with the specified name is not in the prescribed folder or path is not valid. You can go two ways: check the file in a variablelogical expression (applying the operator “!”, for example) or to use the method is_open() :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <iostream> #include <fstream> using namespace std; int main() { setlocale(LC_ALL, "rus"); ifstream file ("d:\\1\\файл.txt"); if (!file) { cout << "Файл не открыт\n\n"; return -1; } else { cout << "Все ОК! Файл открыт!\n\n"; return 1; } } |
So everything will work fine and the file will open:
Now try to enter the name of the folder is not 1, and 2 ifstream file ("d:\\<span style="color: #ff0000;"><strong>2</strong>\\файл.txt”); and restart the program. Since the specified folder name, we did not create, then the file, naturally, It can not be opened:
The second embodiment checks using the methodis_open() :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include <iostream> #include <fstream> using namespace std; int main() { setlocale(LC_ALL, "rus"); ifstream file ("d:\\1\\файл.txt"); if (file.is_open()) // вызов метода is_open() cout << "Все ОК! Файл открыт!\n\n" << endl; else { cout << "Файл не открыт!\n\n" << endl; return -1; } } |
Methodis_open() return 1, If the file is found and successfully opened. otherwise returns 0 and work code prescribed in the block else.
If the file is not open – desirable to handle the error. Usually, if all of the work program associated with the file they write a certain message to the console, and put out of the program. When serious errors common to return a code execution (number), which will characterize one or another mistake. The codes for each type of error the author of the program can invent their own. One of the ways to handle errors in the program, we have considered in the article Exceptions in c++.
If the file is opened successfully, from it you can read.
read the operator>>
As well as in iostream Reading can be arranged by the operator >>, that indicates in which variable will be made to read:
1 2 3 4 5 | double d; int i; string s; file >> d >> i >> s; |
considers real, string and integer. row readout end, if there was a space or end of line. It is worth noting, that the operator >> It applied to text files. Reading from a binary file to make the best using the method read().
By the way, this statement is quite convenient, if the task is to split the file into words:
1 2 3 | // Считка слов из файла for(file >> s; !file.eof(); file >> s) cout << s << endl; |
Methods getline() и get()
Reading the character string to the translation of the carriage is made the same as in iostream by getline(). Moreover, it is recommended to use the overloaded version of the function, if you read a line of type string:
1 2 3 4 | //Считка строки из текста string s; getline(file,s); cout << s << endl; |
If you need to read in an array of characters char[], either get() or getline() just as the methods:
1 2 3 4 5 6 7 8 9 10 11 12 | int n = 10; //Создаем буффер для чтения char* buffer = new char[n+1]; buffer[n]=0; //Читаем n символов file.get(buffer,n); //Или так, но до первого пробела file.getline(buffer,n,' '); //выводим считанное cout << buffer; //Освобождаем буффер delete [] buffer; |
The principle is generally the same, as in the analogs of iostream: Shown as a parameter buffer (variable, where the reading will be done), or rather a pointer to a block of memory (if the variable is declared statically: char buffer[255] for example, it is written in the parameters &buffer), specifies the maximum number of readable (in this example n), so as not to overflow has occurred and the output of the buffer limits and the separator character as required, to which will Proofreading (in this example the gap). I hope I did not hurt tread on the trunk fanatics C, if the soot that these two functions on 99% interchangeable, and 95% They may be replaced by read().
Method read()
1 2 3 4 5 6 7 8 9 | //Считка из файла N байт int n=10; //Создаем буффер char* buffer=new char[n+1]; buffer[n]=0; //Читаем в него байты file.read(buffer,n); //выводим их на экран cout<<buffer; delete [] buffer; |
Similar to the previous example?
Actually here the same result – It is considered to be a specified number of characters. The exception only, it is impossible to specify the delimiter. read() used for unformatted input. It is intended primarily to read binary files. Since the text file – a special case of a binary, this method is quite applicable to the text file.
Method close()
closes the file. Even nothing to add. Perhaps the only remark – on, that the file, opened for reading, will not be closed by this method usually does not become worse. Very rare situation, when opened for reading deteriorates file, if you complete the program without closing the file. This damage is associated primarily with non-standard devices such as tape drives Tape or what some artful stream of industrial controllers, but in Feng Shui to remember– open file should be closed. It is considered good form.
Method eof()
Checks whether the file end is reached. That is. whether it is possible from it to continue reading. The above example of the proofreading word operator >> just use this check.
Method seekg()
Installs the current position to the desired, indicates the number. This method is also transmitted positioning method:
- ios_base::end – Read off a new position at the end of the file
- ios_base::beg – Read off a new position from the beginning of the file (absolute positioning)
- ios_base::cur – Jump to n bytes from the current position in the file (по умолчанию)
1 2 3 4 5 | file.seekg(0,ios_base::end); //Стать в конец файла file.seekg(10,ios_base::end); //Стать на 10 байтов с конца file.seekg(30,ios_base::beg); //Стать на 31-й байт file.seekg(3,ios_base::cur); //перепрыгнуть через 3 байта file.seekg(3); //перепрыгнуть через 3 байта - аналогично |
Method tellg()
Sometimes you need to get information about, as already read. This method will help tellg():
1 | cout << "Считано байт: " << file.tellg(); |
It returns a value of type int, which shows how much has already passed in bytes. It can be used in tandem with the method seekg(), To get the file size:
1 2 3 4 | //становимся в конец файла file.seekg(0,ios_base::end); //Получаем текущую позицию cout << "Размер файла (в байтах): " << file.tellg(); |
As an example of the binary reading methods can be dismantled so class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | class ReadStream { private: //Приватное поле - файл ifstream f; public: //Конструктор, открывающий файл ReadStream(const char *FileName){ f.open(FileName); if(!f.is_open()) cout<<"Файл не открыт"; } //Метод чтения массива символов-байт с указанной позиции //который возвращает этот массив char *read(int position, int count){ if(!f.is_open()) return 0; f.seekg(position); if(f.eof()) return 0; char *buffer=new char[count]; f.read(buffer,count); return buffer; } //Деструктор, закрывающий файл ~ReadStream(){ f.close(); } }; |
Similar wrapper classes useful, if there are problems reading from a binary whole structure.
Videos about working with files in C ++:
f.seekg(9, ios_base::end);
f.read(ch,8);
file size (in bytes): -1Press any key to continue . . .
What about the method .seekp()? he is also responsible for the idea of some kind of pointer, and there is no disk imaging……
Well, the code-style, pancake. All blocks and arguments is stuck on one another, any gaps, or tab, Only in ReadStream, although, suspect, there was just a piece of neatly stolen. Fortunately though she writings not bydlokod…
+++a similar view: great website design, code clearance – g…but!
I think, proofreading words from a file do better to sell through … while, than through for.
do {
file >> s;
cout << s << endl;
} while (!file.eof());
The choice of cycle depends on the operator's knowledge of the number of iterations: if the number is unknown – then it is better to use WHILE, if you know – It recommended FOR (To read in Polyakova. YU., advanced-level textbook).
Sooooo little information. I think, somewhere between 1 and 2 % of the total capacity of PL “C/C++”. We have a lecture at the university is all about telling other methods, much shorter and more convenient. Here are some of them:
The difference between these two methods is, that getline () retrieves from the flow limiting character (\0), while get () this does not. neither one, no other method does not record the restrictive character in the buffer.
The For loop is very well done)
if (!file)
{
cout << "Файл не открыт\n\n";
return -1;
}
Hello, Why is there a return statement in the if statement???? what is it for? what does it do in this example?
Completion of the function, in this case the main function.
Can you write something about creating files at runtime and how to work with them if you do not know the exact folder(I don't even have a disk “d” and this code won't work for me)