我想连接一个包含路径和文件名的fileName。然后我可以打开并写出来。但我没有这样做。
char * pPath;
pPath = getenv ("MyAPP");
if (pPath!=NULL)
//printf ("The current path is: %s",pPath); // pPath = D:/temp
string str = "test.txt";
char *buf = new char[strlen(str)];
strcpy(buf,str);
fullName = ?? // how can I get D:/temp/test.txt
ofstream outfile;
outfile.open(fullName);
outfile << "hello world" << std::endl;
outfile.close();
答案 0 :(得分:4)
string str = "test.txt";
char *buf = new char[strlen(str)];
strcpy(buf,str);
应该是
string str = "test.txt";
char *buf = new char[str.size() + 1];
strcpy(buf,str.c_str());
但毕竟,你甚至都不需要那样。 std::string
支持operator+=
的连接和char*
的构造,并公开返回c样式字符串的c_str
函数:
string str(pPath); // construction from char*
str += "test.txt"; // concatenation with +=
ofstream outfile;
outfile.open(str.c_str());
答案 1 :(得分:1)
#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
using namespace std;
int main() {
char* const my_app = getenv("MyAPP");
if (!my_app) {
cerr << "Error message" << endl;
return EXIT_FAILURE;
}
string path(my_app);
path += "/test.txt";
ofstream out(path.c_str());
if (!out) {
cerr << "Error message" << endl;
return EXIT_FAILURE;
}
out << "hello world";
}
答案 2 :(得分:1)
char * pPath;
pPath = getenv ("MyAPP");
string spPath;
if (pPath == NULL)
spPath = "/tmp";
else
spPath = pPath;
string str = "test.txt";
string fullName = spPath + "/" + str;
cout << fullName << endl;
ofstream outfile;
outfile.open(fullName.c_str());
outfile << "hello world" << std::endl;
outfile.close();
答案 3 :(得分:0)
string fullName = string(pPath) + "/" + ...
string fullName(pPath);
fullName += "/";
fullName += ...;