调试时打开文件时出错

Error opening file when debugging

本文关键字:出错 文件 调试      更新时间:2023-10-16

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

// 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> >

试试这个:

// 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 中,这应该有效。剩下的就看你自己了。相对路径有效,您需要确保文件是程序查找它的位置(或相反的"圆形")。如果您不确定出了什么问题,请尝试打印出当前路径。