Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write program in C++ (25 points) Because text files can grow very large, some co

ID: 3699412 • Letter: W

Question

Write program in C++

(25 points) Because text files can grow very large, some computer systems supply a handy utility program that displays the head and tail of a file where the head is the first four lines and the tail is the last four lines. Write a program that asks the user to type in a file name and then displays the head of the file, a line of dots (three or four dots will do), and the tail of the file. If the file is eight lines long or less, just display the entire file 5. Note: you will create your own file to text. You will need to submit your program and your test file.

Explanation / Answer

#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;

// Function to read the contents of file and displays it
void readFile(string fileName)
{
// ifstream object declared
ifstream rFile;
// To store header, body and footer part of file
string head, body, footer;
// Opens the file for reading
rFile.open(fileName.c_str());
// Check that file can be opened or not
// is_open() function returns true if a file is open and associated with this stream object.
// Otherwise returns false.
if(!rFile.is_open())
{
// Displays error message
cout<<" Error: Unable to open the file! "<<fileName;
return;
}// End of if condition

// Loops 3 time for header part of the file
for(int c = 0; c < 3; c++)
{
// Read the line from the file
getline(rFile, head);
// Display it
cout<<head<<endl;
}// End of for loop

// Loops till end of file
while(!rFile.eof())
{
// Reads one line of data from file and stores it in body
getline(rFile, body);
// Checks if the data is four dots then come out of the loop
if(body.compare("...."))
break;
// Display the data
cout<<body<<endl;
}// End of while loop

// Loops till end of the file for footer data
while(!rFile.eof())
{
// Read the line from the file
getline(rFile, footer);
// Display it
cout<<footer<<endl;
}// End of while loop

// Close the file
rFile.close();
}// End of function

// main function definition
int main()
{
// To store file name
string fileName;
// Accepts file name from the user
cout<<" Enter the file name: ";
cin>>fileName;
// Calls the function to read file contents
readFile(fileName);
}// End of main function

Sample Output:

Enter the file name: testFile.txt
....
This is the header part.
....
Check this demo.
Read the file contents.
Display the file contents.
....
This is footer part.
....

testFile.txt file contents

....
This is the header part.
....
This is a demo.
Check this demo.
Read the file contents.
Display the file contents.
....
This is footer part.
....

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote