一次读取文件,放入一个char buffer里面的问题【解决即给分】

xiaohou0701 2008-12-03 11:16:06
应该可以换个问法,有多少的方法,可以一次性把文件读入一个buffer?


ifstream test;
test.open(fileDir);

//get the length of the file;
int temp = test.tellg();//record the current site.
test.seekg(0,ios_base::end);//move to the end of the file
int len = test.tellg();//get the length
test.seekg(temp);//move back to the original site
char* buffer = new char[len];

test.read(buffer,len);


读出来的buffer,除了正文之外,还有很多“屯屯屯屯屯屯屯屯屯屯屯屯屯”。怎样才能只读取正文?

...全文
171 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
lc19890326 2008-12-03
  • 打赏
  • 举报
回复
将文本文件读入内存的时候,会将ASCII码转换成二进制码
你那个乱码可能与编码有关 具体的我也不是很清楚
xiaohou0701 2008-12-03
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 Chiyer 的回复:]
C/C++ code

#include "iostream"
#include "fstream"
using namespace std;

int main()
{
char fileDir[] = "test.txt";

ifstream test;
test.open(fileDir, ios_base::binary); // 这里,用2进制打开

//get the length of the file;
int temp = test.tellg();//record the current site.
test.seekg(0,ios_base::end);//move to the end of the file
int len = te…
[/Quote]

解决。能告诉我一下原理吗?或者相关参考资料。
xiaohou0701 2008-12-03
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 cftxlin 的回复:]
引用楼主 xiaohou0701 的帖子:
应该可以换个问法,有多少的方法,可以一次性把文件读入一个buffer?


C/C++ code
ifstream test;
test.open(fileDir);

//get the length of the file;
int temp = test.tellg();//record the current site.
test.seekg(0,ios_base::end);//move to the end of the file
int len = test.tellg();//g…
[/Quote]

此办法不行。。一开始,打开的就是文件头的位置了嘛。
星羽 2008-12-03
  • 打赏
  • 举报
回复


#include "iostream"
#include "fstream"
using namespace std;

int main()
{
char fileDir[] = "test.txt";

ifstream test;
test.open(fileDir, ios_base::binary); // 这里,用2进制打开

//get the length of the file;
int temp = test.tellg();//record the current site.
test.seekg(0,ios_base::end);//move to the end of the file
int len = test.tellg();//get the length
test.seekg(temp);//move back to the original site
char* buffer = new char[len + 1];

test.read(buffer,len);
buffer[len] = 0;

cout<<buffer<<endl;

return 0;
}


  • 打赏
  • 举报
回复
[Quote=引用楼主 xiaohou0701 的帖子:]
应该可以换个问法,有多少的方法,可以一次性把文件读入一个buffer?


C/C++ code
ifstream test;
test.open(fileDir);

//get the length of the file;
int temp = test.tellg();//record the current site.
test.seekg(0,ios_base::end);//move to the end of the file
int len = test.tellg();//get the length
test.seekg(te…
[/Quote]

char* buffer = new char[len];
test.read(buffer,len);
//是不是应该换成
char* buffer = new char[len-temp];
test.read(buffer,len-temp);


65,211

社区成员

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

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