Write a Program to read and write a data to and from a file. code example
Example 1: write in file in c
#include<stdio.h>
int main(){
FILE *out=fopen("name_of_file.txt","w");
fputs("Hello File",out);
fclose(out);
return 0;
}
Example 2: 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 3: 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;
}