Learn to Code via Tutorials on Repl.it!

← Back to all posts
C++ Fstream File Handling ( Tutorial )
JaydenSavarinat (14)
#include <iostream>
#include <fstream> // Inlcude fstream library to handle files
#include <cstring>

/************************************************

- - - - - KEY - - - - -

ofstream - Creates and writes to files

ifstream - Reads from files

fstream - creates, reads, and writes to files

************************************************/

int main() {

  std::string FileText;

  // Creates a file named "File.txt" and opens it
  std::ofstream MyFile("File.txt");

  // Writes "Hello File!" to "File.txt"
  MyFile <<  "Hello file! \n";
  MyFile <<  "Hello file! \n";
  MyFile <<  "Hello file! \n";

  // Closes "File.txt"
  MyFile.close();

  // Reads text from "File.txt"
  std::ifstream Read("File.txt");
  while (getline(Read, FileText)) {

    // Outputs all text from "File.txt"
    std::cout << FileText << std::endl;

  }

}
Comments
hotnewtop
JaydenSavarinat (14)

@qerewrad Thank you! Also, feel free to join my developer group. Click below to join. https://repl.it/teams/join/qqepyfbajpqyfnooryesrpdcdfpifnkp-ReplitDevTeam