WAP to perform write operation in the file
Objective
Write a C++ program to perform a write operation to a file.
Algorithm / Approach
- Include the
<fstream>header for file operations. - Create an object of
ofstream(Output File Stream). - Ask the user for a filename and open it using
out.open(name, ios::out). - Use a
whileloop to read characters from the keyboard usinggetchar()until a stop character (@) is pressed. - Write each character to the file object:
out << c. - 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). ofstreamspecifically 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 standardios::outmode will completely overwrite its previous contents.
Complexity
Time Complexity
O(n) - Where n is the number of characters written.
Space Complexity
O(1)