可视文件打开以C++读取

visual File opening for reading in C++

本文关键字:C++ 读取 文件 可视      更新时间:2023-10-16

我正在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);

它的工作。