You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++文件I/O求助:使用文件名无法找到.txt文件,仅全路径可打开

问题原因与解决方案

当你仅使用scores.txt作为文件名时,程序会在当前工作目录而非你的.cpp文件所在目录寻找文件,这就是找不到文件的核心原因。默认情况下,IDE(比如Visual Studio、Code::Blocks)的工作目录通常不是源文件所在的inclass目录,而是项目根目录或者编译输出的Debug/Release文件夹。

解决方法:

  • 方法1:确认当前工作目录
    在代码中添加一段输出当前工作目录的代码,明确程序到底在哪个目录下查找文件:

    #include <cstdlib>
    #include <iostream>
    #include <string>
    #include <ctime>
    #include <fstream>
    #include <direct.h> // Windows平台头文件,Linux环境替换为<unistd.h>
    using namespace std;
    int main() {
        // 输出当前工作目录
        char cwd[1024];
        if (_getcwd(cwd, sizeof(cwd)) != nullptr) {
            cout << "当前工作目录:" << cwd << endl;
        } else {
            cerr << "获取工作目录失败" << endl;
        }
    
        string fName;
        string lName;
        int score;
    
        ifstream myFile("scores.txt");
        if (myFile.is_open()) {
            while(myFile >> fName && myFile >> lName && myFile >> score) {
                cout << fName << " " << lName << " " << score << endl;
            }
            myFile.close();
        }
        else{
            cout << "No file found" << endl;
        }
        return 0;
    }
    

    运行后,将scores.txt复制到输出的工作目录中,即可正常打开文件。

  • 方法2:修改IDE的工作目录
    直接把程序的工作目录设置为源文件所在的C:\Users\mfkha\cmsc202\inclass:

    • Visual Studio:右键项目 → 属性 → 调试 → 工作目录,输入该路径
    • Code::Blocks:右键项目 → 属性 → 构建目标 → 工作目录,输入该路径
      设置完成后,直接使用scores.txt即可找到文件。
  • 方法3:使用相对路径
    如果不想修改IDE设置,可通过相对路径指向文件。比如若工作目录是C:\Users\mfkha\cmsc202,则路径可写为inclass\\scores.txt(Windows平台需使用双反斜杠转义)。

内容的提问来源于stack exchange,提问作者Muhammad Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 13:07:35