I need to get the filename out of a full path name and am getting unexpected output and a fault.
I am compiling the code on Visual C++ .NET.
The code for this function is as follows:
Code:
virtual void fileSelected(const char *n) {
string name = n; //copy file path
int startName = 0; //initialize position where filename starts
int endName = 0; //initialize position where the filename ends
string filename; //stores filename without path or extension
editor->getSceneGraph()->saveFile(n);
editor->setLoadedFileName(n);
ofstream a_file ( "file.txt" ); //open file
for (int i = 0; i < name.length(); i++) //iterate through given path to find where filename begins and ends
{
if (name[i]= '/')
startName= i;
if(name[i] = '.')
endName = i;
}
startName= startName+1; //filename actually starts immediately after the last '/'
//filename = name.substr(startName+1,name.length()-endName); //get filename from name <---FAULTS HERE
//save information to file
a_file << filename << endl; //the filename that I need
a_file<< n << endl; //path input to function
a_file << name << endl; //string that is copied from path
a_file<< startName << endl; //where the filename starts in the path
a_file<< name.substr(name.length()-4, 4)<<endl; //file extension
a_file.close();
}
If the path is C:\ProgramFiles\test.doc, the output should be:
C:\ProgramFiles\test.doc
C:\ProgramFiles\test.doc
17
.doc
I am getting:
C:\Program Files\test.doc
.........................
25
....
Also, when I un-comment the line
Code:
filename = name.substr(startName+1,name.length()-endName); //get filename from name
I get the Microsoft Development Environment error "Unhandled exception at 0x7c812a5b in Interactive Architecture.exe: Microsoft C++ exception: std:ut_of_range @ 0x0012ee60."
Does anyone know what might be causing my problems and have any suggestions?
Thank you,
JackR