Skip to content

Instantly share code, notes, and snippets.

@MannyGozzi
Created July 9, 2018 19:45
Show Gist options
  • Save MannyGozzi/3c1690e5c5f65c9cb3ea09e4cddcda2c to your computer and use it in GitHub Desktop.
Save MannyGozzi/3c1690e5c5f65c9cb3ea09e4cddcda2c to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
#include <fstream> //allows use of file stream
#include <sstream>
int main()
{
// constructor for file streams implements the open() function
// example -> ifs.open("foo.txt") = ifs("foo.txt")
//std::ios::app means write data from the end of the file
std::ofstream ofs("foo.txt", std::ios::app); // ofstream -> write only -> creates file if file does not exist
std::ifstream ifs("foo.txt"); // ifstream -> read only -> reads from file if it exists
std::ostringstream oss;
std::string str;
//if file is empty write to it
if (ofs.is_open() && (ifs.peek() == std::ifstream::traits_type::eof())){
std::cout << "File was written to" << "\n";
ofs << "Yay... Files!!!!" << std::endl;
}
//if file has already been written to, don't write to it
else if (ofs.is_open()){
std::cout << "File has already been written to" << std::endl;
}
//something bad happened
else {
std::cout << "Error occured while outputting to file" << std::endl;
}
//close to prevent further access
ofs.close();
//sets position to beginning of "foo.txt" and
//also calls std::ifstream::clear()
//which resets eof bit
ifs.seekg(0, std::ios::beg);
std::cout << "\nReading from file\n";
std::cout << "-------------------" << std::endl;
//if the file isn't empty then print it
if (ifs.peek() != std::ifstream::traits_type::eof())
{
//using ostringstream because we are only outputting to a string
while (std::getline(ifs, str))
{
oss << str << "\n";
}
std::cout << oss.str() << std::endl;
}
else
{
//should never run
std::cout << "File was empty" << std::endl;
}
std::cin.get();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment