Click here to Skip to main content
16,018,442 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I have created a Windows form app and part of it includes getting a name out of a text box and appending it to a directory in order to write to a file in that directory.

The top level will always be C:\Programs\PROGRAMS\

Here is what I have right now for my constructor (This is not how I actually want to do it, just wanted to provide some idea of what I'm looking at):

createFile::createFile(string name)
{
	string path = "C:\\Programs\\PROGRAMS\\" + name + "\\" + name + ".txt";	
}


So for example a file I would like to write to could be:
C:\Programs\PROGRAMS\ATP-8878B\ATP-8878B.txt
and I would like to be able to use
ofstream outFile;
outFile.open(path);

The error I get is: Attempting to read or write from protected memory.
at the first strcat() call.

The parameter (const char* name) can be changed to another type, as it needs to be converted from a String^ anyway, if you think that could be helpful. From what I've found path needs to end up being a const char* in order to call outFile.open(path);

Any ideas on a better way I can do this?
Thanks in advance for any help.

EDIT:
Modified original code.
Posted
Updated 16-Jun-11 10:53am
v3

Sorry to waste anyone's time who read this... apparently I just wasn't thinking clearly.

After changing the code in the constructor to what it now in my top post, the solution was simply:

ofstream outFile;
outFile.open(path.c_str());
 
Share this answer
 
The reason your other code wasn't working was that you had:

createFile::createFile(const char* name)
{
    char* path = "C:\\Programs\\PROGRAMS\\";

    path = strcat(path, name);
    path = strcat(path, (const char*)'\\');
    path = strcat(path, name);
    path = strcat(path, (const char*)'.txt');
}


when you should've probably had something like this:
createFile::createFile(const char*name)
{
    char path[] = "C:\\Programs\\PROGRAMS\\";

    strcat(path, name);
    strcat(path, (const char*)"\\");
    strcat(path, name);
    strcat(path, (const char*)".txt");
}
 
Share this answer
 
Comments
obp42 16-Jun-11 17:17pm    
Yeah I'm not too sure what exactly I was thinking when I was typing that garbage in... haha oh well I guess it's been a long day. Thanks again Albert.
Albert Holguin 16-Jun-11 17:24pm    
happens... my initial solution was to look at your const calls, but then I looked closer and they were all correct...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900