[英]File opening for reading in C++
I am developing a project in Visual Studio 2012 and I can not figure out why this code always return with "The file can not be opened!", because tram.exe and stops.txt is in the same (Debug) folder. 我正在Visual Studio 2012中开发一个项目,我无法弄清楚为什么这个代码总是返回“文件无法打开!”,因为tram.exe和stops.txt在同一个(Debug)文件夹中。
#include <iostream>
#include <fstream>
int main (int count, char *arguments[]) {
if (count > 1) {
ifstream input("stops.txt");
if (input.is_open()) {
} else {
cout << "The file can not be opened!";
}
}
}
Visual Studio, by default, will set your Working Directory to $(ProjectDir)
- that is, the folder where your vcxproj lives - this won't be the same as the folder your exe gets written out to, so you won't find your text file in the current directory. 默认情况下,Visual Studio会将您的工作目录设置为$(ProjectDir)
- 即您的vcxproj所在的文件夹 - 这与您的exe写出的文件夹不同,因此您将找不到您当前目录中的文本文件。
Either manually change the working directory Project Properties->Configuration Properties->Debugging to match the target path, or change your filename to point to the full (or relative) path. 手动更改工作目录Project Properties-> Configuration Properties-> Debugging以匹配目标路径,或更改文件名以指向完整(或相对)路径。
Find out what the current working directory of your running process is with 找出正在运行的进程的当前工作目录
http://msdn.microsoft.com/en-us/library/windows/desktop/aa364934(v=vs.85).aspx http://msdn.microsoft.com/en-us/library/windows/desktop/aa364934(v=vs.85).aspx
Example: 例:
unsigned int length = 0;
char* workingDirectory;
length = GetCurrentDirectory(0, NULL); // How large should my buffer be?
workingDirectory = new char[length]; // Allocate buffer
GetCurrentDirectory( (DWORD) length, (LPTSTR) workingDirectory); // Fill with string
std::cout << workingDirectory << std::endl; // Output string
delete [] workingDirectory; // Make sure to delete it
You can put this into a function 你可以将它放入一个函数中
void getWorkingDirectory(std::string& dir)
{
unsigned int length = 0;
char* buffer;
length = GetCurrentDirectory(0, NULL);
buffer = new char[length];
GetCurrentDirectory( (DWORD) length, (LPTSTR) buffer);
dir = buffer;
delete [] buffer;
}
NOTE: I haven't tested this. 注意:我没有测试过这个。
Use the below line of code: 使用以下代码行:
ifstream input("stops.txt", std::fstream::out); ifstream输入(“stops.txt”,std :: fstream :: out);
Its working. 它的工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.