简体   繁体   English

当前 Windows position C++ 的文件 I/O

[英]File I/O from current Windows position C++

I have not yet found a definitive answer about this.我还没有找到关于这个的明确答案。 I am trying to have access to files in subfolders from my.EXE.我正在尝试从 my.EXE 访问子文件夹中的文件。 When I have asked before, people tell me to use the absolute location ie "c:/game/info/" if I wanted to access something in /info/当我之前问过时,人们告诉我使用绝对位置,即“c:/game/info/”如果我想访问 /info/ 中的某些内容

But it is completely unreasonable for me or anyone to assume that someone is going to use their program from the same directory.但是对于我或任何人来说,假设有人将从同一目录中使用他们的程序是完全不合理的。 What if the user only has a D drive?如果用户只有一个 D 盘怎么办? That sort of thing.之类的东西。

So my question is: how can I access a file in a subdirectory from my executable without relying on the entire path?所以我的问题是:如何在不依赖整个路径的情况下从可执行文件访问子目录中的文件?

Your title says "Windows", so I'll give a WinAPI-specific answer.你的标题是“Windows”,所以我会给出一个 WinAPI 特定的答案。

On Windows, you can find your application directory with GetModuleFileName(NULL, ...) , and PathRemoveFileSpec .在 Windows 上,您可以使用GetModuleFileName(NULL, ...)PathRemoveFileSpec找到您的应用程序目录。 Then PathAppend will make the full path to your data files.然后PathAppend将为您的数据文件创建完整路径。

Or you can store the data inside you.exe file as Win32 resources , so they never get separated.或者您可以将 you.exe 文件中的数据存储为Win32 资源,这样它们就永远不会分开。


Please note that this approach generally works only for read-only access to data files.请注意,这种方法通常仅适用于对数据文件的只读访问。 If you try to write files in your application directory, you might be blocked by ACLs (depending on install location and local security settings of the computer).如果您尝试在应用程序目录中写入文件,您可能会被 ACL 阻止(取决于计算机的安装位置和本地安全设置)。

Use GetModuleFileName (Retrieves the fully-qualified path for the file that contains the specified module. The module must have been loaded by the current process.)使用GetModuleFileName (检索包含指定模块的文件的完全限定路径。该模块必须已被当前进程加载。)

char strExePath [MAX_PATH];
GetModuleFileName (NULL, strExePath, MAX_PATH);

You'll then need to extract the folder path (someone has already posted how to do that), and combine your path.然后,您需要提取文件夹路径(有人已经发布了如何执行此操作),并组合您的路径。

Make or use an installer that asks the user where to install the executable and writes that path to the registry in a well-known location for later reference.制作或使用安装程序,询问用户在何处安装可执行文件,并将该路径写入注册表中的知名位置以供以后参考。

if you use:如果您使用:

#include <fstream>

ifstream stream("file");

it will be working.它会起作用的。 "file" is file in directory with your exe. “文件”是您的 exe 目录中的文件。 Of course if you want go up or down in folders hierarchy use "..\file" or "folder\file"当然,如果您希望 go 在文件夹层次结构中向上或向下,请使用“..\file”或“folder\file”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM