Read and Write File in C++ example Program

You have to create two files named students_file.txt and file.html. Below is the program code:-

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream x;
ofstream y;
string array[15][6];
x.open("students_file.txt");
if(x.fail())
{
cout<<"your file is not open";
return 0;
}
else
cout<<"your file is in processing"<<endl;
for(int i=0;i<15;i++)
{
for(int j=0; j<6; j++)
{
getline(x,array[i][j],'    ');
}
}
x.close();
y.open("file.html");
y << "<!DOCTYPE html>" << endl << "<html>" << endl << "<head> \n <style> \n table, th, td { border: 1px solid black; border-collapse: collapse;} th, td { padding: 15px; \n }  \n th {background-color: rgba(245, 185, 117, 0.59);} </style> \n </head> \n" ;
y<<    "<body> \n <style> \n body{ background-image: url('2.jpg');} \n </style>" << endl << "<table style='width:100%;'>" << endl;
for(int i=0; i<1; i++)
{
y << "<tr>";
for(int j=0; j<6; j++)
{
y << "\t <th><b>" << array[i][j]<< "</b></th> \n";
}
y << "</tr>";
}
for(int i=1;i<15;i++)
{
y <<"<tr>";
for(int j=0; j<6; j++)
{
y << "\t <td>" << array[i][j] << "</td>\n";
}
y << "</tr>";
}
y << "</table>" << endl << "</body" << endl << "</html>";
y.close();
return 0;
}

Contents of the file students_file.txt are:

Sr.No    REG ID    NIC    Full NAME    GENDER    FATHER NAME
1    120669    6110171022039    Meeran Nabi Khan    M    Irfan Nabi Kahn
2    120649    6110179159843    Awais Khan Mughal    M    Muhammad Pervaiz Mughal Late
3    120690    3740551675849    Mohammad Taimoor Ahmed    M    Mohammad Tanvir
4    120668    3330360563415    Muhammad Waqar Khan    M    Arshad Khan
5    120645    4210152838337    Zaheeruddin Babar Siddiqui    M    Abul Hassan Siddiqui
6    120635    3420234599433    Nasir Iqbal    M    Zafar Iqbal Hailvi
7    120616    6110173919729    Syed Basit Abbas    M    Syed Waqar Haider Naqvi
8    120619    3740680978413    Bilal Mahmood Malik    M    Tariq Mahmood Malik
9    120603    6110105071187    Muhammad Zeeshan    M    Muhammad Azhar Shehzad Cheema
10    120685    3210214061429    Azaz Ahmad    M    Sher Zaman
11    120623    3210260511247    Muhammad Arham Shahzad    M    Shahzad Qaisar
12    120641    3420164950097    Muhammad Hassan Sohail    M    Sohail Yousaf
13    120615    3720401292559    Ehtisham Ahmad    M    Munir Ahmad
14    120709    1320230053833    Abdullah Khan    M    Dr. Marghoob Ahmed


After compiling and executing the program you will see the following output by opening the file.html.


If you have any questions then let me know in comments, thanks.

4/5 - (2 votes)

royal52
royal52

I’m a DevSecOps Software engineer by profession and a SEO hobbyist. I’m passionate about everything Software, including game development.

We will be happy to hear your thoughts

Leave a Reply

HellGeeks
Logo