ifstream打开文件总是失败!

Ori_old 2010-11-11 11:30:36

#include "stdafx.h"
#include <iostream>
#include <istream>
#include <fstream>

using namespace std;

typedef std::string String;

void loadDirect(const String& filename)
{

std::ifstream fp;

fp.open(filename.c_str(), std::ios::in | std::ios::binary);
if(!fp)
{
cout<<"打开 失败。";
}


}

int _tmain(int argc, _TCHAR* argv[])
{
cout<<"Hello\n";
loadDirect("abc.txt");
return 0;
}

abc.txt是随便写一个文件。放在debug目录,放在System32目录下也不行。
...全文
3297 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq120848369 2010-11-11
  • 打赏
  • 举报
回复
#include <iostream>
#include <fstream>
using namespace std;

typedef std::string String;

void loadDirect(const String& filename)
{

std::ifstream fp;
fp.open(filename.c_str(), std::ios::in | std::ios::binary);

if(fp.bad()) //误你妹,没有!
{
cerr<<"打开失败"<<endl; //cerr打印错误,否则出不来东西.
}
}

int main()
{
loadDirect("d:\\abc.txt");
return 0;
}

zhanshen2891 2010-11-11
  • 打赏
  • 举报
回复
在VC里面调试执行或者运行默认的当前目录都是工程所在目录
塞文 2010-11-11
  • 打赏
  • 举报
回复
看你从哪里启动你的exe文件咯。如果你直接在IDE中启动。abc.txt文件可以放在项目文件夹。但是如果你进入debug目录或release目录,那就要放在和exe文件同一个目录下才可以。
你可以加上一个条件,判断文件的位置在什么地方。例如:
if ( !loadDirect("..\\abc.txt") )
{
loadDirect("..\\debug\\abc.txt");
}
即,当加载失败时,尝试从其他目录加载。
sbdt123 2010-11-11
  • 打赏
  • 举报
回复
学习了,真实恍然大悟啊
maoxing63570 2010-11-11
  • 打赏
  • 举报
回复
还有就是打开文件后要记得关闭文件
maoxing63570 2010-11-11
  • 打赏
  • 举报
回复

#include <iostream>
#include <istream>
#include <fstream>

using namespace std;

typedef std::string String;

void loadDirect(const String& filename)
{

std::ifstream fp;
fp.open(filename.c_str(), std::ios::in | std::ios::binary);
cout<<fp.rdbuf();
fp.clear();
if(!fp.bad())
{
cout<<"打开 失败。";
}


}

int main()
{
cout<<"Hello\n";
loadDirect("abc.txt");
return 0;
}

你哭了就可了啊,还是不可以,嘻嘻,你打开后流可能出现了不正确的状态,但不是你打开失败了,你可以用我上面的代码看下你的可以读出来么,我的是可以读出来的
zongzihe 2010-11-11
  • 打赏
  • 举报
回复
放错目录了。。。
Ori_old 2010-11-11
  • 打赏
  • 举报
回复
嗯,放在工程目录下。--快哭了。
ouyh12345 2010-11-11
  • 打赏
  • 举报
回复
GetLastError
hai040 2010-11-11
  • 打赏
  • 举报
回复
放在工程目录下
Ori_old 2010-11-11
  • 打赏
  • 举报
回复
实践证明:abc.txt放在工程目录下就好了。谢谢!!谢谢各位!
libinfei8848 2010-11-11
  • 打赏
  • 举报
回复
再不行你就绝对路径试试吧,但一般不推荐这个

65,212

社区成员

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

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