Skip to content

Instantly share code, notes, and snippets.

@vineethm1627
Created March 2, 2021 06:35
Show Gist options
  • Save vineethm1627/3c8815885cd703b29970320284dd21dc to your computer and use it in GitHub Desktop.
Save vineethm1627/3c8815885cd703b29970320284dd21dc to your computer and use it in GitHub Desktop.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream MyFile;
// open the file
MyFile.open("test.txt");
MyFile << "Some text. \n";
// close the file.
MyFile.close();
}
@vineethm1627
Copy link
Author

Under certain circumstances, such as when you don't have file permissions, the open function can fail.
The is_open() member function checks whether the file is open and ready to be accessed.

#include <iostream>
#include <fstream>
using namespace std;

int main() {
  ofstream MyFile("test.txt");

  if (MyFile.is_open()) {
   MyFile << "This is awesome! \n";
  }
  else {
   cout << "Something went wrong";
  }
  MyFile.close();
}

@vineethm1627
Copy link
Author

Reading information from the file, line by line.

#include <iostream>
#include <fstream>
using namespace std;

int main () {
    ofstream MyFile1("test.txt");
    
    MyFile1 << "This is awesome! \n";
    MyFile1.close();

    string line;
    ifstream MyFile("test.txt");
    while ( getline (MyFile, line) ) {
        cout << line << '\n';
    }
    MyFile.close();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment