We can make use of stream to open, edit, and close files very easily. I learned them today and would like to put some tips down for future reminder.
1. Include the iostream and fstream.
2. Use the ofstream to open and write a file:
ofstream outputFile(fileName, std::ios_base::out/std::ios_base::app)
The fileName should be char* type. If it is a string, convert it to char* using fileName.c_str();
std::ios_base::out means to overwrite the whole file from the beginning;
std::ios_base::app means to write from the end of the file, leaving all of the existing data unchanged;
there are still some other modes, see http://www.cplusplus.com/reference/iostream/ofstream/ofstream/;
also there is a third parameter, int_Prot. Not very clear how to use it yet.
after this definition of the temporary variable, we can use outputFile.open(fileName, std::ios_base::out/std::ios_base::ape) to open and add data.
3. Use the ifstream to open and read a file. Be careful about the ios::in | ios::binary if read a binary file. It is very different from the default setups.
4. Dynamic fileName/load multi files
Use the following pattern to create a editable filename
char filename[256]/* = "slice001image015echo001.fdf"*/;
sprintf_s(filename, 256, "Data/slice001image%03decho001.fdf", theFrameNum);
"/" defines the folder path of the file. "%03d" is the number to identify different files, which means 3-digit integer. Using this we can use loops to read different files in sequence at one time.
5. Close Files
Never forget to close a file when finishing the operation before opening it again! Or it will not be read again in the same function layer.
No comments:
Post a Comment