1

実行時に新しいテキスト ファイルを作成するプログラムを作成しています。複雑すぎることはありません。プログラムをコンパイルした後、ターミナルを使用して実行すると期待どおりに新しいファイルが作成されますが、ダブルクリック実行を使用して新しいファイルを作成できないことに気付きました。
ここに私が使用しているコードのサンプルがあります:

#include <fstream>
#include <iostream>
using namespace std;

int main() {
    ofstream outputFile("NewFile.txt");
    outputFile << "Some text";
    outputFile.close();
    printf("File created successfully!\n");
    return 0;
}

なぜこうなった?

4

1 に答える 1

0

次の方法で問題を解決できました。

#include <fstream>
#include <iostream>
using namespace std;

int main(int argc,char *argv[]) {

    // dirsep is a pointer to the file name
    char *dirsep = strrchr( argv[0], '/' );
    // If it's not null, set the value to 0, seperating the directory
    // from the file name
    if( dirsep != NULL ) *dirsep = 0;

    // Change the current working directory to the path of the executable
    if(chdir(argv[0]) != 0) printf("The file will be created in the home directory");

    ofstream outputFile("NewFile.txt");
    outputFile << "Some text";
    outputFile.close();
    printf("File created successfully!\n");
    return 0;
}

私を正しい方向に向けてくれた @jogojapan に感謝します。

于 2012-12-14T03:40:10.330 に答える