C++ – How Create a Text File and Write in It




cpp tutorials
cpp tutorials

C++ – Creating and writing to a file.

In C++ we have the following classes to perform output and input operations of characters from/to files:

ofstream:  class to write on files
ifstream: class to read from files
fstream:  class to both read and write from/to files.

So in order to create a file and write to it we will use ofstream class.

Let’s say we want to create a file called codebind.txt and write something in it.

// Creating and writing to a file - C++
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream file;
  file.open ("codebind.txt");
  file << "Please writr this text to a file.\n this text is written using C++\n";
  file.close();
  return 0;
}

Output:

[file codebind.txt]
Please writr this text to a file.
 this text is written using C++

 


Partner Sites

VideoToGifs.com

EasyOnlineConverter.com

SqliteTutorials.com





2 Comments

  1. #include
    #include
    using namespace std;
    int main()
    {
    ofstream fs ; //name decleartion
    char c [500]; //variable declearation to store the writen data
    fs.open(“D:\project\file\test.txt”); //location fo file is in D drive

    cout<<"Enter textn" ; //asking the user to input the text
    cin>> c; //storing the content written by the user.
    fs << c ; //file system writing the information in the text file
    fs.close(); // file closure
    return 0;
    }
    Since i am Learning, so far what i have understood i have tried.

Leave a Reply

Your email address will not be published.


*