Hello,
Today i am playing with IO's, and here is the example that i want to work out:
Code:#include <iostream> #include <fstream> #include <cstdlib> #include <cstring> void openFile(std::fstream &out, std::string fileName, int x){ switch (x){ case 'rt': out.open (fileName.c_str(),std::ios::in); break; case 'wt': out.open (fileName.c_str(),std::ios::out); break; case 'at': out.open (fileName.c_str(),std::ios::app); break; case 'rb': out.open (fileName.c_str(),std::ios::in | std::ios::binary); break; case 'wb': out.open (fileName.c_str(),std::ios::out | std::ios::binary); break; } if ( !out.is_open()){ std::cout << "Cannot open file: in_file! Line:" << __LINE__<< std::endl; exit(EXIT_FAILURE); } } int main(int argc, char **argv){ char buffer[100]; std::fstream out_file; std::fstream in_file; openFile(out_file,"example.txt",'wt'); // WORKS out_file << "Radi-"; out_file.close(); out_file.clear(); openFile(in_file,"example.txt",'rt'); // WORKS in_file.read(buffer, 5); std::cout << buffer; in_file.close(); in_file.clear(); openFile(out_file,"example.txt",'at'); // DOES NOT APPEND out_file << "Radio"; out_file.close(); out_file.clear(); openFile(in_file,"example.txt",'rt'); // WORKS but prints out this strange character in_file.read(buffer, 10); std::cout << buffer; in_file.close(); in_file.clear(); openFile(out_file,"example.bin",'wb'); // not binary - correction out_file << "Radik\n"; out_file.close(); out_file.clear(); openFile(out_file,"example.bin",'rb'); // not binary - correction out_file.read(buffer, 5); std::cout << buffer; out_file.close(); out_file.clear(); return 0; }
so i am opening and closing the files and reading and writing to them. the problems are stated in the code. Can someone explainwhat is going on..
output: Radi-Radi-Radik



LinkBack URL
About LinkBacks


