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

在GoogleTest中进行C++文件读取测试失败的问题排查与解决

GoogleTest测试中文件读取失败的排查与解决

问题描述

我在学习使用GoogleTest测试C/C++程序时,遇到了TEST()函数中读取文件失败的问题,测试代码如下:

#include <iostream>
#include <fstream>
#include <filesystem>

TEST(IOTest, ReadFile) {
    std::string filename = "input.txt";
    std::string buffer;
    std::ifstream ifs(filename, std::ios::binary);
    std::filesystem::path cwd = std::filesystem::current_path();
    std::cout << "Current directory path: " << cwd << std::endl;
    std::cout << "Current file path: " << __FILE__ << std::endl;
    ASSERT_TRUE(ifs.is_open());
}

排查细节

测试运行后输出显示当前工作目录为C:\Users\Tong\source\repos\BookLibrary\Debug,但我错误地将input.txt放在了C:\Users\Tong\source\repos\BookLibrary\GoogleTest\Debug目录下,尝试使用./input.txt作为文件路径也没能解决问题。

解决办法

最终确认问题出在文件放置路径上,正确的存放路径应该是项目根目录下的Debug文件夹:C:\Users\Tong\source\repos\BookLibrary\Debug,将input.txt移动到该目录后,测试即可正常通过。

内容的提问来源于stack exchange,提问作者Tong Zhao

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 03:45:41