Pages

Tuesday, October 18, 2011

Writing a file (char by char)

To read a file one char at a time, we can use the "put()". The put() writes a character to a file. To write multiple characters we can either use the put() inside a loop or we can use functions that read the data string by string.

Syntax
ofstream.put(char);

Example 1 : Lets see how the put() can be used to write a single character in the file.

#include "conio.h"
#include "fstream.h"
#include "iostream.h"
void main()
{
 clrscr();
 ofstream of("file1.txt");
 char c;
 cout<<"\nEnter a character to be stored in the file  : ";
 cin>>c;

cout<<"\nSaved";
 of.put(c);
 of.close();
}


When you run the program, it asks for a character that you want to store or save in the file. The character that you enter will be stored in the file named "file1.txt", that you can open in My Computer to verify.

Output
Enter a character to be stored in the file : P
Saved

To verify the writing process.
Open the file "file1.txt" using My Computer or click "DOS Shell" and type "type file1.txt" at the command prompt.

0 comments:

Post a Comment