There is enough wrong with the code supplied to OP to be worth a quick going over in addition to pointing the OP in a useful direction.
First, no test for NULL on the call to getenv. If MODEL_MERGE
doesn't exist, NULL is returned and then used in string copies. BOOM!
Second, new
ing all those arrays. Dynamically allocate only as a last resort. new
must be pared with at least one delete
, depending on the code's flow, to return the allocated memory for reuse when no longer needed. Since there seems to no need to dynamically allocate and the sizes of the arrays are known, they should have been defined as char templatePath[100];
. Less memory management to be dealt with and effectively no possibility of leakage.
Third renders point two obsolete. Rather than using char arrays, use strings where possible. Not only do they handle all of the memory management, including resizing as needed rather than trampling out of bounds, for you, they also perform routine tasks like copying and appending with much less fuss. This bit I'll demonstrate below.
Proper use of cin and cout is well detailed on a number of sites so I won't go over it here.
Also note I've removed the need for using namespace std;
by explicitly stating the namespace at use. Read why using namespace std;
is often a bad idea.
#include <fstream>
#include <iostream>
int main()
{
char * Model_MergePath = getenv("MODEL_MERGE");
if (Model_MergePath != NULL)
{ //MODEL_MERGE is defined
std::string path(Model_MergePath); //replace icky and fault-prone char array
std::string templatePath = path; // copy strings with =
std::string outputPath; // not assigning path here so I can demonstrate
//something else later
std::string inFileLoc; // new throw away variables for user input.
std::string outFileLoc; // could use the same var for both. I didn't for clarity
std::cin >> inFileLoc; // get input
templatePath += inFileLoc; // append to strings with +=
std::cin >> outFileLoc;
outputPath = path + outFileLoc; // concatenate strings with +
// validate paths for correctness and possible intrusion attempts here
// this, I'm afraid, is up to the OP as the security requirements are unknown
std::cout << "temp: " << templatePath << std::endl;
std::cout << "out: " << outputPath << std::endl;
//input output file streams for reading/writing to files
std::ifstream readFile(templatePath);
// older C++ compilers may require a c-style string as the file path
std::ofstream outFile(outputPath.c_str());
// do stuff with readFile and outFile
// remove the deletes that should have corresponded to the replaced `new`s
return 0;
}
else
{ //MODEL_MERGE is NOT defined
std::cerr << "Cannot find environment variable MODEL_MERGE. Exiting." << std::endl;
return -1;
}
}