c++ 如何读取文件中的所有字符?

如何用c++读取某一文件里的所有字符,并保存至string.h里声明的一个字符串类string的一个成员里?

大侠帮忙!!!

急用!

只需要在每次读取的时候判断是否为最后一个字符即可,和一般的读取文件方式并没有什么不同。

相比之C和其他几种主流编程语言,c++对于文件的读取操作是十分方便简单的。

在过程中有几个问题需要注意:

    检查是否打开文件并且可以进行读取操作。

    存放读取结果的变量是否足够大。

    读取工作完成后需要关闭文件指针。

如下是针对要求编写的代码:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

const string GetFileName(void);
void ReadFile(const string strFileName);

int main(void)
{
    ReadFile(GetFileName());
    cout << endl;

    return 0;
}

const string GetFileName(void)
{
    string strFileName;
    cout.setf(ios::right);
    cout.width(30);
    cout << "输入文件的路径:";
    cin >> strFileName;

    return strFileName;
}

void ReadFile(const string strFileName)
{
    string text;

    ifstream in(strFileName.c_str());

    if (!in)
    {
        cout.width(15);
        cout << "文件打开失败" << endl;
    }

    while (in >> text)
    {
        cout << text;
    }

    in.close();
    in.clear();
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-01-18
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int getFullFile(ifstream &ifs, string &str)
{
char currch;

str.erase();
while( !ifs.eof() )
{
ifs.get(currch);
if ( ifs.bad() )//there is an unrecoverable error.
return -1;
if (currch == '\0')
break;
else
str += currch;
}
return str.length();
}

int main()
{
ifstream tfile( "c:\\test.txt", ios::binary);
string abc("");

while ( !tfile.eof() )
{
if ( getFullFile(tfile, abc)
cout<<abc<<endl;
else
break;
abc.erase();
}
return 0;
}本回答被提问者采纳
第2个回答  2019-03-29
比如说,文件的最后一个字符串是a
,
当你在循环体里面读入后,
文件指针
指在最后这个位置,但它还不是文件尾的标志EOF,
所以,此时while(!infile.eof())将顺利通过,只有当这一个进入循环体内再次读文件时,
才会读到EOF标志,此后infile.eof()才会为真
解决的办法:把判断放在循环体内,读文件之后,其他操作之前
if(!infile.eof())
break;
第3个回答  2008-09-27
最简洁的做法是用ios::rdbuf():

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

bool getFileStr(string filename, string str)
{
ifstream src(filename.c_str());
if(src.is_open())
{
str = src.rdbuf().str();
src.close();
return true;
}

retrun false;
}
第4个回答  2008-09-26
楼上的
相似回答