【问题标题】:How to create files corresponding to program location?如何创建与程序位置对应的文件?
【发布时间】:2016-11-24 20:54:20
【问题描述】:

有没有办法使用 C++ 和 C++ 程序的位置在计算机上创建文件?我希望能够在多台计算机上使用这个程序,但每台计算机都有自己不同的目录。例如,如果我想在用户目录中创建 test.txt 文件,有没有办法将文件的路径与程序文件的位置相对应,因为“用户”在用户名上有所不同。

【问题讨论】:

  • 使用GetModuleFileName函数。
  • ... 但根据具体情况,查找用户的 Documents 文件夹(或者可能是应用程序数据文件夹)的位置可能会更好 - 请参阅 MSDN 中的 Known Folders

标签: c++ windows file


【解决方案1】:

只要您在 Windows 上,您就可以使用 API GetUserName,然后使用 SetCurrentDirectory API 更改工作目录,然后使用 CreateFile 或 fstream 创建您的文件:

#include <iostream>
#include <windows.h>
#include <fstream>
#include <string>
using namespace std;


int main()
{

    ULONG len = 50;
    LPSTR lpBuffer = (LPSTR)GlobalAlloc(GPTR, len);
    GetUserName(lpBuffer, &len);
    cout << lpBuffer << endl;
    // don't forget to clean when you're done:

    string str = "C:\\Users\\";
    str += lpBuffer;
    str += "\\test.txt";
    cout << str << endl;

    ofstream out(str.c_str());
    if(out.fail())
        perror("Opening failed");
    out << "Hello " << lpBuffer;

    out.close();

    GlobalFree(lpBuffer);


    GlobalFree(lpBuffer);

    return 0;
}

此程序获取当前用户名并在其文件夹中创建文件并在其中写入“Hello”'yourusername'

【讨论】:

  • 不能保证用户的个人资料总是 C:\Users\,事实上在很多情况下它不会。此外,配置文件是放置文件的错误位置。
  • 这个答案有多个问题:1 使用GlobalAlloc 作为缓冲区,也可以是堆栈分配的; 2 绝对确保代码失败,用户名中有某些 Unicode 字符; 3构造一条可能存在也可能不存在的路径; 4 使用 std::basic_ios::fail() 错误的方式; 5lpBuffer 上调用GlobalFree 两次。
猜你喜欢
  • 2015-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-26
  • 1970-01-01
相关资源
最近更新 更多