如何用ifstream读取文件信息保存到字符数组中

jmghoul 2012-12-20 10:47:56
我想把一个txt文件中所有信息读取到char型数组中 现在不知道如何定义这个数组大小 如果定义固定大小的话文件太大又读取不全。有什么办法么
...全文
619 9 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
引用 5 楼 ForestDB 的回复:
多看看标准库文档。
http://www.cplusplus.com/reference/istream/istream/seekg/

# include <iostream>
# include <fstream>
# include <ios>

using namespace std;

int main()
{
ifstream in("y.cpp");
in.seekg(0, ios::end);
int length = in.tellg();
in.seekg(0, ios::beg);
char * buffer = new char[length];
in.read(buffer, length);
in.close();
cout.write(buffer, length);
delete [] buffer;

return 0;
}


威武!
Binzo 2012-12-21
  • 打赏
  • 举报
回复
new 动态内存分配。
AnYidan 2012-12-21
  • 打赏
  • 举报
回复
size_t fread(void *ptr, size_t size, size_t nobj, FILE *stream) fread reads from stream into the array ptr at most nobj objects of size size. fread returns the number of objects read; this may be less than the number requested. feof and ferror must be used to determine status. 如果返回值 等于 指定读出的数值,说明可能未读完
ForestDB 2012-12-21
  • 打赏
  • 举报
回复
或者看看系统的api,比如Linux下的stat函数,也能得到文件的大小。
ForestDB 2012-12-21
  • 打赏
  • 举报
回复
多看看标准库文档。 http://www.cplusplus.com/reference/istream/istream/seekg/

# include <iostream>
# include <fstream>
# include <ios>

using namespace std;

int main()
{
    ifstream in("y.cpp");
    in.seekg(0, ios::end);
    int length = in.tellg();
    in.seekg(0, ios::beg);
    char * buffer = new char[length];
    in.read(buffer, length);
    in.close();
    cout.write(buffer, length);
    delete [] buffer;

    return 0;
}
nocodelife 2012-12-21
  • 打赏
  • 举报
回复
先获取文件的大小,然后动态申请
jmghoul 2012-12-20
  • 打赏
  • 举报
回复
读取文件大小的函数有么? 用new来申请数组大小么 char a = new char[?]
东大坡居士 2012-12-20
  • 打赏
  • 举报
回复
or 先读文件大小。再动态申请
东大坡居士 2012-12-20
  • 打赏
  • 举报
回复
全局定义大点

70,023

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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