可视文件打开以C++读取
visual File opening for reading in C++
我正在Visual Studio 2012中开发一个项目,我无法弄清楚为什么这段代码总是返回"文件无法打开!",因为tram.exe和stops.txt在同一个(调试)文件夹中。
#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 会将您的工作目录设置为 $(ProjectDir)
- 即您的 vcxproj 所在的文件夹 - 这与你的 exe 被写出的文件夹不同,因此您将无法在当前目录中找到您的文本文件。
手动更改工作目录"项目属性"->"配置属性"->"调试"以匹配目标路径,或更改文件名以指向完整(或相对)路径。
找出正在运行的进程的当前工作目录是什么
http://msdn.microsoft.com/en-us/library/windows/desktop/aa364934(v=vs.85).aspx
例:
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
你可以把它放到一个函数中
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;
}
注意:我还没有测试过这个。
使用以下代码行:
ifstream input("stops.txt", std::fstream::out);
它的工作。
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 无法找到/读取配置文件.conf-FileIOException
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++将文本文件中的数据读取到结构数组中
- 正在将csv文件读取为双精度矢量
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 为什么在读取文件大小时文件IO速度会发生变化
- 正在读取二进制文件(is_open)
- 如何在c++中从文本文件中逐行读取整数
- SSH通过/sbin/SSH无法读取RSA密钥文件(从控制台运行)
- 独立读取-修改-写入顺序
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- 一种在C++中读取TXT配置文件的简单方法