Write a C++ program in which user will continuously enter data into a text file and program should terminate when user press ESC key. Keep the program as simple as you can use any c++ compiler CodeBlocks is recommended.
Concept usedFile pointer FILE * represents pointer to a variable of FILE type
function fopen() is used to open a file and takes two parameters.
- Name of a file with its extension in double quotes it can include file path or not
for example "NewFile.txt" or "c://NewFile.txt" if path is not specified it will open a
file in current directory where your .c or .cpp file is. - File opening mode it represent the purpose of opening of file and what operation will be perform on the file reading, writing, or editing. In this example file mode will be "w" for
writing
fopen prototype FILE *fopen(const chr *fileName, const char *mode );
Program explanation
- A while loop is used and will terminate when user will press esc key. To get the characters a function getche() is used from conio.h which will store in char variable and store into the file using putc() function.
- On pressing esc to avoid any other character written into the file an if condition is used which will write space into the file when user will press escape.
C++ source code
#include <iostream>
#include <stdio.h>
#include <conio.h>
using namespace std;
int main()
{
FILE *fp;
char ch;
fp = fopen("text.txt","w");
cout<<"Type characters to write into file"<<endl;
cout<<"Press Esc to close file\n\n\n"<<endl;
while(ch!=27) {
ch=getche();
if(ch==27) {
putc(' ',fp);
} else {
putc(ch,fp);
}
if(ch==13) {
cout<<"\n";
putc('\n',fp);
}
}// end of while loop
fclose(fp);
cout<<"\n\n\n";
return 0;
}
Recommended: For good learning do experiment with code and examine the output
0 comments:
Post a Comment