为什么在 Windows 上无法使用 fstream 创建/写入文件? [英] Why doesn't creating/writing to file with fstream work on windows start up?

查看:50
本文介绍了为什么在 Windows 上无法使用 fstream 创建/写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这里我得到了这个每个人都明白的小程序.

So here I got this little program which everyone obviously understands.

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 文件.为什么会这样,我该如何避免?

This program works just fine, however, the problem is that if I have added it to run on windows start up(in registries SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run), the programs starts fine, but it does not create example.txt file. Why is that and how do I avoid it?

推荐答案

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

It tries to create the file in the current working directory for the process, since you specified a relative path.

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

Because there is no way to specify the working directory in the Windows\CurrentVersion\Run registry setting, the working directory is inherited from the parent process. The parent process is the shell, explorer.exe which has a working directory of C:\Windows\system32. Since (assuming UAC is enabled) your user doesn't have rights to that folder, no file is created.

这篇关于为什么在 Windows 上无法使用 fstream 创建/写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆