This code works! But if I save first the strings objects in 1 string object and then convert it to a C-string, the problem you mentioned disappears?
|
Exactly. You are now creating your own object on the stack,
filePath, as a copy of the temporary object.
filePath persists for as long as it remains in scope, which means that your
address1 pointer is pointing to valid memory for as long as
filePath is in scope.
The following, however, doesn't make any sense:
1 2 3 4
|
if (file1 != NULL)
file1 = fopen(address1, "w");
else
file1 = fopen(address1, "r");
|
At the point where you have that if statement,
file1 is uninitialised, which means the value is undefined. It might be NULL, or it might be something else, but that that depends entirely on the C++ compiler you're using.
Its value certainly has nothing to do with whether or not the file exists; how could it, when you haven't yet done anything to associate
file1 with any particular file?
Using the uninitialised value of
file1 to determine the behaviour of your program makes no sense.