Skip to content

Instantly share code, notes, and snippets.

@krysseltillada
Created July 18, 2015 15:38
Show Gist options
  • Save krysseltillada/afddac613426ca730712 to your computer and use it in GitHub Desktop.
Save krysseltillada/afddac613426ca730712 to your computer and use it in GitHub Desktop.
file streams in a function way
#include <iostream> /// std::cout; std::cin; std::endl; std::cin::badbit; std::ostream; std::istream; std::getline; std::cin::setstate;
#include <fstream> /// std::ofstream; std::ifstream; std::ofstream::out; std::ofstream::app;
#include <string> /// std::string;
std::ostream &write(std::ostream &os, const std::string &file, const std::string &str) { /// writes a data in a file if overwrited then old data will erased
std::fstream file_m (file, std::ofstream::out); /// declares and define a filestream named file_m that has default mode of implicit std::ofstream::trunc and explicit std::ofstream::out
os << str << std::endl; /// writes the data in the file
return os; /// returns the stream state
}
std::ostream &write_app (std::ostream &os, const std::string &file, const std::string &str) { /// preserves the data in a file and adds some data to it
std::fstream file_m (file, std::ofstream::app); /// declares and define a filestream file_m that has a default mode of implicit std::ofstream::out and explicit std::ofstream::app
os << str << std::endl;
return os;
}
std::istream &read (std::istream &is, const std::string &file, std::string &str) {
std::fstream file_m (file, std::ifstream::in);
if (!file_m) { /// if file is failed display message and set the stream condition to failbit (or badbit for fatal error)
std::cout << "file " << file << " failed to open " << std::endl;
is.setstate(std::cin.badbit); /// sets the stream into badbit
return is;
}
while (std::getline(file_m, str)) /// reads the data and stores to str
;
return is;
}
int main ()
{
std::string display;
write (std::cout, "sample.txt", "hello world"); /// arguments std::ostream object, filename, writes anything
read (std::cin, "sample.txt", display); /// arguments std::istream object, filename, variable to be stored
std::cout << display << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment