如何将一个文本文件的所有内容读出来?

chido 2002-11-05 09:12:29
如何将一个文本文件的所有内容读出来,放到一个char型数组或者指针里?
试了好几个函数,都是到空格或者回车就会终止.
...全文
85 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
topikachu 2002-11-05
  • 打赏
  • 举报
回复
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>


using namespace std;

string read_file_into_string(const string&);

int main()
{
string strFile;
cout<<"pls input a filename with path"<<endl;
cin>>strFile;

string FileContext=read_file_into_string(strFile);


cout<<FileContext<<endl;
}

string read_file_into_string(const string& strFile)
{
ifstream ifile(strFile.c_str());
ostringstream buf;
char ch;
while (buf && ifile.get(ch))
buf.put(ch);

return buf.str();

}

用的是标准库,不用考虑delete,不用考虑平台依赖性,不用担心缓冲是否不够:)
wzt2000 2002-11-05
  • 打赏
  • 举报
回复
char buffer[8096];
char *str=new char[256];
memset(buffer,0,8096);
while(!feof(fp))
{
if(fgets(str,256,fp)==NULL)
break;
strcat(buffer,str);
}
delete []str;
gucs 2002-11-05
  • 打赏
  • 举报
回复
gz
GZCompiler 2002-11-05
  • 打赏
  • 举报
回复
用fread()函数。
zxm954712 2002-11-05
  • 打赏
  • 举报
回复
#include "stdio.h"
#include "stdlib.h"
#include "memory.h"
#include "string.h"

void main()
{
FILE *fp;
char *p;
char caBuf[256];
char caTemp[8092];

fp = fopen("a.txt", "r");
if (fp == NULL) {
printf("open file error\n");
exit(1);
}

memset(caBuf, 0x00, sizeof(caBuf));
memset(caTemp, 0x00, sizeof(caTemp));
p = fgets(caBuf, 256, fp);
if (p != NULL) {
memcpy(caTemp, caBuf, strlen(caBuf));
}
memset(caBuf, 0x00, sizeof(caBuf));
p = fgets(caBuf, 256, fp);
while(p != NULL) {
strcat(caTemp, caBuf);
memset(caBuf, 0x00, sizeof(caBuf));
p = fgets(caBuf, 256, fp);
}

caTemp[strlen(caTemp)] = 0x00;
printf("caTemp is %s", caTemp);
fclose(fp);
}

black_snail 2002-11-05
  • 打赏
  • 举报
回复
#include <stdio.h>

#define MAX 100000;
char cContent[MAX];

int main(void)
{
FILE *stream;
int i=0;
/* open a file for reading */
stream = fopen("DUMMY.FIL", "r");

while (!feof(stream))
{

/* read a character from the file */
cContent[i]=fgetc(stream);
i++;

}

/* close the file */
fclose(stream);
return 0;
}

69,369

社区成员

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

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