在 C++ 中打开文件时遇到问题

发布于 2024-12-26 05:39:50 字数 565 浏览 1 评论 0原文

我在打开文件进行阅读时遇到问题,而且我不太清楚我做错了什么,也许我提供路径的方式有问题,但我不知道。

/*
output:
Where is the conversion table ?
/Users/awiebe/Documents/Langara\ Assignments/CPSC1160/CURRENCYCODES.txt 
Unable to open file
*/


StringFloatMap readFile(string path)
{
    //fstream filestr ("test.txt", fstream::in | fstream::out);
    ifstream filestr;
    const char* cPath = path.c_str();
    filestr.open(cPath);

    if (filestr.is_open())
    {
        filestr.close();
    }
    else
    {
        cout << "Unable to open file" << endl;
    }
/*…*/
}

I'm having trouble opening a file for reading, and I can't quite figure out what I'm doing wrong, maybe something is wrong with how i give my path, but i don't know.

/*
output:
Where is the conversion table ?
/Users/awiebe/Documents/Langara\ Assignments/CPSC1160/CURRENCYCODES.txt 
Unable to open file
*/


StringFloatMap readFile(string path)
{
    //fstream filestr ("test.txt", fstream::in | fstream::out);
    ifstream filestr;
    const char* cPath = path.c_str();
    filestr.open(cPath);

    if (filestr.is_open())
    {
        filestr.close();
    }
    else
    {
        cout << "Unable to open file" << endl;
    }
/*…*/
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

缱绻入梦 2025-01-02 05:39:50

您不需要转义路径中的空格字符(例如,您可以删除文件名中的 \)。

You don't need to escape the space character in the path (e.g., you can remove the \ in your filename).

妥活 2025-01-02 05:39:50

不需要 cPath 变量(但可能有利于调试)

我建议打印失败消息。添加

#include <cstring>
#include <cerrno>

cout << "Unable to open file:" << errno << ':' << strerror(errno) << std::endl;

The cPath variable is not needed (but maybe good for debugging)

I would suggest printing the failure message. Add

#include <cstring>
#include <cerrno>

and

cout << "Unable to open file:" << errno << ':' << strerror(errno) << std::endl;
扛刀软妹 2025-01-02 05:39:50

只需去掉“\”并给他路径:
例如:

/Users/awiebe/Documents/Langara 作业/CPSC1160/CURRENCYCODES.txt

由于您使用字符串类,因此无需对空格使用转义序列。

Just get rid of the "\" and give him the path:
e.g.:

/Users/awiebe/Documents/Langara Assignments/CPSC1160/CURRENCYCODES.txt

Since you use the string class there is no need to use escape sequences for the whitespaces.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文