C Language Write a C program to determine if the entire contents of a text file
ID: 3745150 • Letter: C
Question
C Language
Write a C program to determine if the entire contents of a text file is a single palindrome. If the contents are palindromic, your program should print out: "<filename> is a palindromic file." and then terminate by calling exit (0). If the file is not palidromic, then your program should say: " <filename> is not a palindromic file. It differ at characters <left position> and <right position>." and then terminate by calling exit (-1). (*Replace left and right positions within the file where the first difference occurs.)
Your program shoud copy the char array stored in argv[1] into another char array using the strcpy () function. Assume the file name has 1024 chars at most.
Please provide a plentiful amount of comments to help the code readability.
*I am using Emacs and gcc in case that potentially makes a difference in the code design.
Explanation / Answer
#include<iostream>
#include<algorithm>
#include<string.h>
#include<fstream>
using namespace std;
using std::cout;
using std::endl;
int filename(int argc, char* argv[])
{
//error checking
if (argc < 1 || argc > 4) {
cout << "Usage: -c( - clear the contents of file) <Filename>, any msg" << endl;
exit(EXIT_FAILURE);
}
char filename[64];
char message[1024];
//set variables to command arguments depending if -c option is specificed
if (argc == 4)
{
strlcpy(filename, argv[2], 64);
strlcpy(message, argv[4], 1024);
}
else
{
strlcpy(filename, argv[1], 64);
strlcpy(message, argv[4], 1024);
}
int fd; //file descriptor
fd = open(filename, O_RDWR | O_CREAT, 00000); //open file if it doesn't exist then create one
fchmod(fd, 00000);
return 0;
}
int main() {
filename(argc,argv[])
string line="", line_rev="";
ifstream infile;
infile.open("Text file name");
do{
infile>>line;//reading the line of a text file
line_rev=line;
reverse(line_rev.begin(), line_rev.end());
if(line==line_rev)
cout<< "%s"is a palindrome,filename<<endl;
else
cout<< "%s"is not a palindrome,filename<<endl;
}while(getline(infile, line));
//if(infile.is_open()){cout<<"open"<<endl;} //to check if file is open or not
//else{cout<<"unable to open"<<endl;}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.