Sign in to follow this  
BEHOLDER192875

String manipulation in MSVC++ 2008 Express

Recommended Posts

void OpenFile(char *filename) { int ix, iy, iz; // open filename if (!(fp = fopen(filename,"r"))) return; // count \ to make sure the directory is reset to its original directory iz = 0; ix = strlen(filename); for(iy=0; iy<ix; iy++) if (filename[iy] == '\\') iz++; // set filename to nothing but the directory for(iy=ix; iy>0; iy--) { if (filename[iy] == '\\') { filename[iy] = 0; // causes crash break; } filename[iy] = 0; // causes crash } } For some reason this crashes it every time. Does anyone know why? EDIT: Nevermind. Apparantly MSVC++ 2008 Express doesn't like it when you try to modify a char* as a input variable. Just for your notes as well.

Share this post


Link to post
Share on other sites
You were probably passing a string constant as a parameter to the function (like "C:\SOME\DIRECTORY\SOME_FILE"). You can't write to a string constant. There's probably an option somewhere in your compiler to make the type of constant strings be `char const *', instead of simply `char *'. That would have caught the error in compile time.

Share this post


Link to post
Share on other sites
I don't even think there's a way for a string literal not to be considered a const char*, so I'd rather guess someone has been abusing const_cast and entered the realm of undefined behavior?

Share this post


Link to post
Share on other sites
Since the actual issue has been solved...


void OpenFile(const std::string &filename)
{
std::ifstream is(filename.c_str());
if(is.fail()) return;

filename=filename.substr(0,filename.find_last_of("\\/"));
}


Welcome to 2008. [smile]

[Edited by - EasilyConfused on September 18, 2008 5:29:40 AM]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this