将const char*类型变量用来当文件名读取文件为什么会失败?

ynney_2011 2012-03-26 11:15:45
例子代码如下:
const char* ch="D:\\测试\\1.txt";
fin.open(ch);
if(!fin)
cout<<"read error"<<endl;

输出为:read error
为什么?
...全文
491 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
Spy 2012-03-26
  • 打赏
  • 举报
回复
中文路径吧
三尺青萍 2012-03-26
  • 打赏
  • 举报
回复
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
const char* ch="D:\\测试\\1.txt";
ifstream fin(ch);
fin.is_open();
if(!fin)
cout<<"read error"<<endl;
return 0;
}
用is_open()做就没错误。open()如果函数成功执行,将返回一个空的指针,函数调用setstate(failbit)。
我是初学者,也不是很懂
wintree 2012-03-26
  • 打赏
  • 举报
回复
检查一下你的文件名字。。肯定是因为没读取到啊!
一根烂笔头 2012-03-26
  • 打赏
  • 举报
回复
试试用_T转换一下

#include <tchar.h>
const char* ch=_T("D:\\测试\\1.txt");
qiuxin315 2012-03-26
  • 打赏
  • 举报
回复
我也决定是locale的问题
http://blog.csdn.net/qiuxin315/article/details/7394512
Jim_King_2000 2012-03-26
  • 打赏
  • 举报
回复
中文路径的话,需要修改console的编码和程序的locale,比较麻烦。推荐使用宽字符流。
  • 打赏
  • 举报
回复
const char* ch="D:\\测试\\1.txt";
txt文件名不能以数字开头
pengchy 2012-03-26
  • 打赏
  • 举报
回复
文件存在吗???
一根烂笔头 2012-03-26
  • 打赏
  • 举报
回复
这个不用构造函数,用open方法,一样的

#include <iostream>
#include <fstream>
#include <tchar.h>

using namespace std;

int main()
{
const char* ch=_T("d:\\文档.txt");//此文件必须存在,否则失败
ifstream fin;
//open( const char* szName, int nMode = ios::in, int nProt = filebuf::openprot );
fin.open(ch);
if(!fin)
cout<<"read error"<<endl;
return 0;
}

一根烂笔头 2012-03-26
  • 打赏
  • 举报
回复

#include <iostream>
#include <fstream>
#include <tchar.h>

using namespace std;

int main()
{
const char* ch=_T("d:\\文档.txt");//此文件必须存在,否则失败
//ifstream( const char* szName, int nMode = ios::in, int nProt = filebuf::openprot );
ifstream fin(ch);
if(!fin)
cout<<"read error"<<endl;
return 0;
}
pathuang68 2012-03-26
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 wjj474957860 的回复:]

中文路径吧
[/Quote]

++
很可能就是这个问题

64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧