调试时打开文件时出错

时间:2014-01-01 18:48:20

标签: c++ visual-studio file-io

当我尝试运行以下程序时:

// ConsoleApplication1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <fstream>
#include <iostream>


int _tmain(int argc, _TCHAR* argv[])
{
    std::ifstream inFile("test.txt");

    if(!inFile.is_open()){
        std::cout << "Doesn't work" << std::endl;
    }

    inFile.close();
    return 0;
}

程序无法打开文件,该文件存在于与可执行文件相同的文件夹中(我也试图放入文件的显式路径:C:\ Users \ ..)

尝试打开文件后,变量inFile的值为:

+ inFile    {_Filebuffer={_Set_eback=0xcccccccc <Error reading characters of string.> _Set_egptr=0xcccccccc <Error reading characters of string.> ...} }    std::basic_ifstream<char,std::char_traits<char> >

1 个答案:

答案 0 :(得分:0)

试试这个:

// ConsoleApplication1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <fstream>
#include <iostream>


int _tmain(int argc, _TCHAR* argv[])
{
    std::ifstream inFile("c:\\test.txt");

    if(!inFile.is_open())
    {
        std::cout << "Doesn't work" << std::endl;
    }

    inFile.close();
    return 0;
}

如果您将文件放到C:\test.txt,这应该有用。其余的由你决定。相对路径有效,您需要确保文件是程序查找的位置(或者反之亦然)。如果您不确定是什么问题,请尝试打印当前路径。