Skip to content

Instantly share code, notes, and snippets.

@willowell
Last active March 6, 2020 20:59
Show Gist options
  • Save willowell/51c7712f0bc7f8f51ab438a39bb13e42 to your computer and use it in GitHub Desktop.
Save willowell/51c7712f0bc7f8f51ab438a39bb13e42 to your computer and use it in GitHub Desktop.
C++17 File Open
// Requires at least C++17
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
int main() {
// Path is relative to executable.
std::filesystem::path filePath = "./out.txt";
if (std::filesystem::exists(filePath)) {
std::cout << "File already exists!" << std::endl;
std::ifstream inFile;
inFile.open(filePath);
if (inFile.is_open()) {
std::cout << "Here are the contents of the file:" << std::endl;
for (std::string buffer; std::getline(inFile, buffer); std::cout << buffer);
} else {
std::cerr << "Unable to open file!\n";
return 1;
}
} else {
std::cout << "File does not exist!\nCreating it now..." << std::endl;
std::ofstream outFile;
outFile.open(filePath, std::ios::trunc);
if (outFile.is_open()) {
outFile << "Hello, World!" << std::endl;
} else {
std::cerr << "Unable to open file!\n";
return 1;
}
outFile.close();
std::cout << "Wrote to file." << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment