gpt4 book ai didi

c++ - 为什么不能在 Windows 上启动时使用 fstream 创建/写入文件?

转载 作者:可可西里 更新时间:2023-11-01 10:01:27 25 4
gpt4 key购买 nike

所以在这里我得到了这个每个人显然都能理解的小程序。

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

int main () {

ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}

这个程序工作得很好,但是,问题是如果我将它添加到在 Windows 启动时运行(在注册表 SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run) ,程序启动正常,但不会创建 example.txt 文件。为什么会这样?我该如何避免?

最佳答案

它会尝试在进程的当前工作目录中创建文件,因为您指定了相对路径。

因为无法在 Windows\CurrentVersion\Run 注册表设置中指定工作目录,所以工作目录是从父进程继承的。父进程是 shell,explorer.exe,其工作目录为 C:\Windows\system32。由于(假设 UAC 已启用)您的用户无权访问该文件夹,因此不会创建任何文件。

关于c++ - 为什么不能在 Windows 上启动时使用 fstream 创建/写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5477573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com