在 C++ 中打开文件时遇到问题
我在打开文件进行阅读时遇到问题,而且我不太清楚我做错了什么,也许我提供路径的方式有问题,但我不知道。
/*
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不需要转义路径中的空格字符(例如,您可以删除文件名中的 \)。
You don't need to escape the space character in the path (e.g., you can remove the \ in your filename).
不需要 cPath 变量(但可能有利于调试)
我建议打印失败消息。添加
和
The cPath variable is not needed (but maybe good for debugging)
I would suggest printing the failure message. Add
and
只需去掉“\”并给他路径:
例如:
由于您使用字符串类,因此无需对空格使用转义序列。
Just get rid of the "\" and give him the path:
e.g.:
Since you use the string class there is no need to use escape sequences for the whitespaces.