Object
Write a program that writes one character at a time to a file until enter key is pressed.
Algorithm
- Create an ofstream object outFile to handle output operations on a file.
- Declare character variable ch.
- Open the file named example5.txt using outFile.open().
- IF the file fails to open,
- Write “Error: Unable to open the file”.
- Exit.
- [End of IF structure.]
- WHILE ch ≠ New line (i.e., Enter key is pressed)
- Reads each character using cin.get() and stores it in ch variable.
- Write ch.
- [End of WHILE loop.]
- Close the file.
- Exit.
Flowchart

C++ Source Code
// program 108
#include<iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outFile; // File stream object
char ch;
outFile.open("example5.txt"); // Open the file for writing
if (!outFile.is_open()) // Check if the file is open
{
cout << "Error: Unable to open the file" << endl;
return 1;
}
cout << "Write text to file and press enter:\n\n";
while (ch != '\n')
{
ch = cin.get();;
outFile.put(ch);
}
outFile.close();
return 0;
}
C Source Code
/*program 108*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fptr;
char ch;
fptr = fopen("example5.txt", "w");
if(fptr==NULL)
{
printf("Error: Unable to open the file");
exit(1);
}
printf("Write text to file and press enter:\n\n");
while(ch != '\n')
{
ch=getchar();
fputc(ch, fptr);
}
fclose(fptr);
return 0;
}
Output
Write text to file and press enter:
Karachi is a beautiful city.
