0

我想在 Desktop/(用户指定的文件夹)中创建名为“Control.h”的文件,并向其中写入文本。我该怎么做呢?(对于mac)........这是我迄今为止所拥有的:

#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);
4

1 回答 1

0
std::ofstream out(std::string(final)+"/Control.h");
// ...
out << mytext; // write to stream
// ...
out.close();

Why are you using const char* strings with, cin, though? Either use cin::getline or use std::string to avoid buffer overflows. In addition, using sprintf is also dangerous. A better solution:

#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);
于 2014-02-16T22:47:44.227 回答