Firstly, everything you do before, do not forget to import “<fstream>”.
1 | include <fstream> |
Three common operations in “<fstream>”
As a noob in C++, I will only introduce these three in this post. If I am gonna be in higher level someday, I will write down more about them, even whole thing.
1 | ofstream //write |
Open a File
In class “<fstream>”, there is an inner function open(), which is work on it through ofstream, ifstream and fstream objects.
1 | f.open(filename, mode, prot) |
There are three parameters in this function, first one is the filename, second is the way to open it( more..) and third one is the character of the file( unusual using).
Here, I would like to say a little bit more about class “<ios>”.
ios::in | open a file for input |
---|---|
ios::out | open a file for output |
ios::ate | initial position: end of the file |
ios::app | output in the end of the file |
ios::binary | open a file via binary |
Normally, we use them in combination. So, we do this way:
1 | fstream f; |
Otherwise, here is also a default way without function open(), cpp has prepare it in . We can use them directly:
1 | ofstream out("...", ios::out); |
Close a File
As open() function, here is also a function for closing, which is close().
After closing, the original object can open another file.
1 | ofstream of; |
Reading and Writing on txt file
Read
Same as outputting in the terminal, we can also use << to write the data into a file. (Extension: end of the post)
1 | void openFile(string fileName){ |
Write
Using >> as well…
1 | void writeFile(string fileName) |
Extension
About cin.ignore(), it is used when you wanna ignore the last input in the terminal. Usually, the first input may effects the next one. It is a solution for that problem, it will clear everything after enter including enter.
1 | #include<iostream> |
Thanks for your reading. I am happy, if it is useful for you.
END
Illustrator / Cagy
Text / Cagy
Editor / Cagy
Design / Cagy