C++在自定义目录中创建文件
问题描述:
我想在Desktop /(用户指定的文件夹)中创建名为“Control.h”的文件,并向其中写入文本。我该怎么做呢? (适用于Mac)........这是我到目前为止有:C++在自定义目录中创建文件
#include <iostream>
#include <fstream>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int main()
{
char game_name [100];
cout << "Game Name: ";
cin >> game_name;
const char* homeDir = getenv ("HOME");
char final [256];
sprintf (final, "%s/Desktop/%s",homeDir, game_name);
mkdir(final,0775);
答
std::ofstream out(std::string(final)+"/Control.h");
// ...
out << mytext; // write to stream
// ...
out.close();
你为什么要使用const char*
串用,cin
有关系吗?请使用cin::getline
或使用std::string
以避免缓冲区溢出。另外,使用sprintf也是危险的。更好的解决方案:
#include <string>
// ...
{
std::string game_name [100];
cout << "Game Name: ";
cin >> game_name;
std::string homeDir = getenv ("HOME");
std::string final=homeDir+"/Desktop/"+game_name;
mkdir(final.c_str(),0775);
在那一个我问如何让它去桌面。我现在问如何在Desktop/givenName中创建一个文件夹,并用名称在其中创建文件 – user3316925