Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to perform write operation in the file

C++ Code Example — File Handling Programs

ADVERTISEMENT

WAP to perform write operation in the file

Objective

Write a C++ program to perform a write operation to a file.

Algorithm / Approach

  1. Include the <fstream> header for file operations.
  2. Create an object of ofstream (Output File Stream).
  3. Ask the user for a filename and open it using out.open(name, ios::out).
  4. Use a while loop to read characters from the keyboard using getchar() until a stop character (@) is pressed.
  5. Write each character to the file object: out << c.
  6. Close the file.
main.cpp
#include<iostream>
#include<fstream>
using namespace std;
class Test {
 public:
 void write() {
  char c;
  char name[10];
  ofstream out;
  cout<<"Enter File Name: ";
  cin.getline(name,10);
  out.open(name,ios::out);
  if(out.is_open()) {
   cout<<"Enter data to save till @\n";
   while((c=getchar())!='@') {
    out<< c;
   }
   cout<<"Written Successfully";
  }
  else {
   cout<<"File can't created";
  }
  out.close();
 }
};
int main() {
 Test t;
 t.write();
 return 0;
}

Expected Output

Enter File Name: apps.txt
Enter contents to store till @
Developed for Beginners @
Written Successfully

Explanation of the Program

  • C++ handles files using streams, just like how it handles standard input (cin) and output (cout).
  • ofstream specifically stands for Output File Stream. It is used exclusively to create new files and write data into them. If the file already exists, opening it in standard ios::out mode will completely overwrite its previous contents.

Complexity

Time Complexity O(n) - Where n is the number of characters written.
Space Complexity O(1)
ADVERTISEMENT