C++ 在哪里放置文件以便阅读?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3097868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 12:02:30  来源:igfitidea点击:

Where to place file in order to read?

c++inputfstream

提问by rEgonicS

Hey, where do I place a text file that I'm trying to read using fstream? In this tutorial, http://www.gamedev.net/reference/articles/article1127.asp, they say

嘿,我应该在哪里放置我尝试使用 fstream 读取的文本文件?在本教程中,http://www.gamedev.net/reference/articles/article1127.asp,他们说

ifstream fin("input.txt");

ifstream fin("input.txt");

where would "input.txt" be located? Before I tried directing a path to the file by doing this "C:\Users\XXXXXXX\Documents\test.in". This however does not seem to work, Incorrect data input with fstream.

“input.txt”会在哪里?在我尝试通过执行“C:\Users\XXXXXXX\Documents\test.in”来指向文件的路径之前。然而,这似乎不起作用,fstream 的数据输入不正确

I'm using CodeBlocks.

我正在使用代码块。

Thanks in advance.

提前致谢。

采纳答案by Collin Dauphinee

input.txt should be in the working directory. Usually the working directory is the directory containing the executable. In the case of Visual Studio, the working directory when run in the debugger can be set in the Debug options.

input.txt 应该在工作目录中。通常工作目录是包含可执行文件的目录。对于 Visual Studio,可以在调试选项中设置在调试器中运行时的工作目录。

回答by James McNellis

It depends on your system, but in most cases, if you open a file with a relative path, it will find the file relative to the working directory of the process (i.e., relative to the location from which you started the program).

这取决于您的系统,但在大多数情况下,如果您打开一个带有相对路径的文件,它将找到相对于进程工作目录(即,相对于您启动程序的位置)的文件。

So, if you simply try to open "input.txt" it will likely look in the directory from which you started the program.

因此,如果您只是尝试打开“input.txt”,它可能会在您启动程序的目录中查找。

回答by DmitryK

I would still say specify path instead of relying on current working directory (although for some reason it didn't work for you before).

我仍然会说指定路径而不是依赖当前的工作目录(尽管由于某种原因它以前对您不起作用)。

Try that: ifstream fin("C:/MyDir1/MyDir2/input.txt");

试试看: ifstream fin("C:/MyDir1/MyDir2/input.txt");

or that: ifstream fin("C:\MyDir1\MyDir2\input.txt");

或者: ifstream fin("C:\MyDir1\MyDir2\input.txt");

Also make sure that your program (account it runs under) has at least Read permission for this file.

还要确保您的程序(在其下运行的帐户)至少对此文件具有读取权限。

回答by Federico Ramos

if you have still interest in Code::Blocks you need to modify the Target Properties, go to Project -> Properties -> Build targetsand change the Executing Working Dirfor the debug/release folder of your project

如果您仍然对 Code::Blocks 感兴趣,您需要修改Target Properties,转到Project -> Properties -> Build targets并更改Executing Working Dir项目的调试/发布文件夹