2012-12-12 62 views
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; 
} 

这究竟是为什么?

+3

它创建相对于当前工作目录的文件。您可以在为应用程序定义图标/按钮时指定所需的当前工作目录。或者,在代码中指定一个绝对路径。 – jogojapan

+0

@jogojapan在这种情况下,使用双击执行时目前的工作目录是什么?它不应该是同一个目录吗? –

+0

我对OS X不太熟悉,但有很多相关问题:https://www.google.com/#hl=zh-CN&q=stackoverflow+os+x+default+working+directory+for+applications&oq=stackoverflow+os + x +默认+工作+目录+ for +应用程序也许有些帮助? – jogojapan

回答

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。