una piccola aggiunta, viene inserito un commento all’inizio per permettere al programma di sapere se il file è già stato modificato, nel qual caso esce senza far nulla
`
#include
#include
#include
using namespace std;
const string bookmarks[] = {“A-C”, “D-F”, “G-I”, “J-L”,
“M-O”, “P-R”, “S-U”, “V-X”, “Y-Z”};
const string token(“– \\textbf{“);
const string modifiedMark = “%makebookmark”;
int main(int argc, char *argv[])
{
if(argc==1)
{
cout << "error: input file not specified";
return 1;
}
ifstream inputFile;
ofstream outputFile;
string inputFileName(argv[1]);
string outputFileName("temp.txt");
inputFile.open(inputFileName.c_str(), ios::in);
if(inputFile.is_open())
{
cout << inputFileName << " opened for reading\n";
}
else
{
cout << "failed to open " + inputFileName;
return 1;
}
outputFile.open(outputFileName.c_str(), ios::out);
if(outputFile.is_open())
{
cout << "temporary file opened for reading\n";
}
else
{
cout << "failed to open " + outputFileName;
return 1;
}
string currentLine;
char buffer[1024];
int lines=0;
bool changeNextLine = false;
bool changeThisLine = false;
size_t found;
int bookPos;
outputFile << modifiedMark << "\n";
while(!inputFile.eof())
{
changeThisLine = changeNextLine;
changeNextLine = false;
inputFile.getline(buffer, 1024);
currentLine = buffer;
if(currentLine == modifiedMark) // file has been already processed
{
cout << "Index file already processed, skipping\n";
return 0;
}
found = currentLine.find(token);
if(found!=string::npos)
{
int pos = int(found)+token.length();
char letter = currentLine[pos];
if((letter-'A')%3 == 0)
{
bookPos = (letter-'A')/3;
cout << "Found letter " << letter << endl;
changeNextLine = true;
}
}
outputFile << buffer << endl;
if(changeThisLine)
{
outputFile << "\\phantomsection\n";
outputFile << "\\pdfbookmark[1]{" << bookmarks[bookPos] << "}"
<< "{indexbookmark" << bookmarks[bookPos][0] << "}\n";
}
lines++;
}
inputFile.close();
outputFile.close();
remove(inputFileName.c_str());
rename(outputFileName.c_str(), inputFileName.c_str());
cout << inputFileName << " succesfully modified\n";
cout << lines << " lines processed\n";
return EXIT_SUCCESS;
}
`