Write a program to write and read a text in/from a file. code example
Example 1: c program to read and write to a file
#include <stdio.h>
int main() {
FILE *fp;
char ch;
fp= fopen ('example.txt', 'r');
while( (ch = getc(fp)) != EOF) {
printf('%ch', ch);
}
fclose(fp);
return 0;
}
Example 2: Write a program to write content into text file.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("sample.txt",ios::out);
if(!file)
{
cout<<"Error in creating file!!!"<<endl;
return 0;
}
cout<<"File created successfully."<<endl;
file<<"ABCD.";
file.close();
file.open("sample.txt",ios::in);
if(!file)
{
cout<<"Error in opening file!!!"<<endl;
return 0;
}
char ch;
cout<<"File content: ";
while(!file.eof())
{
file>>ch;
cout<<ch;
}
file.close();
return 0;
}