Ok, I was trying to write a program that formats a plain text file to the formatting standards of gamefaqs.com (no trailing spaces and no more than 79 characters per line). To my eyes, my code looks perfectly fine and effective. If I run it with anything but a file that can be formatted, it runs as expected. That would lead me to believe the problem is in the format_file function, but I don't know where it is. When I run it with a file that actually contains formattable text, it terminates and gives me this message
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
And ends with status 3 (0x3). Here is the code
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int format_file(string filename);
int main(int argc, char** argv)
{
//next 5 lines only for diagnostic purposes
printf("%d argument%s offered\n",argc-1,argc==2?" was":"s were");
for (int a = 1; a < argc; a++)
{
printf("argv[%d] = %s\n",a,argv[a]);
}
string file;
fstream checkfile;
if (! argc > 1)
{
printf("No file argument was offered\nPlease offer a file to format");
return 50;
}
else
//check arguments 1 after another to see which can be formatted
for (int a = 1; a < argc; a++)
{
checkfile.open(const_cast<char*> (argv[a]), ios::in | ios::ate);
//check if file exists
if (checkfile.fail())
{
printf("%s does not exist\nOperation aborted", argv[a]);
return 40;
}
//check if file is empty
else if (! checkfile.tellg() > 0)
{
printf("%s is empty\nNothing to be formatted", argv[a]);
return 30;
}
//if file exists and contains content, format the file
else
{
format_file(file);
printf("%s formatted successfully", argv[a]);
}
if (checkfile.is_open())
checkfile.close();
}
return 0;
}
int format_file(string filename)
{
ifstream readfile;
ofstream writefile;
string file, line;
unsigned int num = string::npos;
//open readfile for reading and formatting
readfile.open(filename.c_str(), ios::in);
while (! readfile.eof())
{
getline(readfile, line);
//check for words from previous line to add
if (file.substr(file.length()-1) != "\n" && num != string::npos)
line = file.substr(num+1) + line;
//check for trailing spaces
while (line.substr(line.length()-1) == " ")
line.erase(line.length()-1);
//check for lines too long
if (line.length() > 79)
{
num = line.length();
while (line[num] != ' ')
num--;
line[num]='\n';
line += " ";
}
//concatenate line onto file
file+=line;
}
//close readfile
if (readfile.is_open())
readfile.close();
//write the resulting file into the filename
writefile.open(filename.c_str(), ios::out | ios::trunc);
writefile << file.c_str();
//close writefile
if (writefile.is_open())
writefile.close();
return 0;
}
I appreciate any help you may offer.