#include <iostream>
#include <fstream>
#include <cassert>
#include <string>
using std::fstream;
using std::string;
using std::ios;
#define tab " "
// file extensions that the program can handle
// you can add more extenssions if needed
char *fileExt[] = {".txt", ".c", ".cpp"};
void convert_to_html(string fileName);
string getProgName(char *szFileName);
void usage(const char *szProgName);
int main(int argc, char *argv[])
{
std
::cout << "\nHTML File Conversion program\n"; if(argc < 2)
{
string sProgName = getProgName(argv[0]);
usage(sProgName.c_str());
return 1;
}
// converting the file entered by the user into an html file
convert_to_html(argv[1]);
std
::cout << "File Conversion Succeeded!"; return 0;
}
// this is the function that makes the conversion:
// Text File to Html File
void convert_to_html(string fileName)
{
fstream fin(fileName.c_str(), ios::in);
if(!fin.is_open())
{
std
::cerr << "Error while opening \"" << fileName
<< "\"" << std
::endl; assert(fin.good());
}
// creating a name for the file that will have the Html Code in it
string fileName2 = fileName;
int nExtNum = sizeof(fileExt)/sizeof(fileExt[0]);
int nPos = -1, nLen = 0;
for(int i = 0; i < nExtNum; ++i)
{
nPos = fileName2.find(fileExt[i]);
nLen = strlen(fileExt[i]);
if(nPos != string::npos && (nPos + nLen) == fileName2.length())
{
fileName2.erase(nPos, nLen);
fileName2 += ".html";
break;
}
}
// notice: do not remove this line
// it could lead to some unwanted problem:
// the content of the original file could get erased
assert(fileName != fileName2);
fstream fout(fileName2.c_str(), ios::out);
if(!fin.is_open())
{
std
::cerr << "Error while opening \"" << fileName2
<< "\"" << std
::endl; assert(fout.good());
}
fout << "<html>\n";
fout << "<head>\n";
fout << "<title>";
fout << fileName2;
fout << "</title>\n";
fout << "</head>\n";
fout << "<body>\n";
fout << "<font size = 2>\n";
char cChar = 0;
while(fin.get(cChar))
{
switch(cChar)
{
case '\n':
fout << "<br>";
break;
case '\t':
fout << tab;
break;
default:
fout << "&#" << (int)cChar;
}
}
fout << "</font>\n";
fout << "</body>\n";
fout << "</html>";
fin.close();
fout.flush();
fout.close();
}
string getProgName(char *szFileName)
{
string sName = "";
while(*szFileName++)
{
sName += *szFileName;
if(*szFileName == '\\')
{
sName.erase();
}
}
int nPos = sName.find(".exe");
if(nPos == sName.length() - 5)
{
sName.erase(nPos, 5);
}
return sName;
}
void usage(const char *szProgName)
{
std
::cout << "Usage: " << szProgName
<< " <filename>" << std
::endl;}