Code to read a complete file in a C++ string.

13 views
Skip to first unread message

Mickey

unread,
May 10, 2010, 12:21:48 AM5/10/10
to nextgen_engg
Now, there is no trick here. I am just looking for different
approaches. You may use C file I/O also but the content should end up
in a c++ string object.

Regards,
Jyoti

Akhil Bhiwal

unread,
May 15, 2010, 11:32:59 AM5/15/10
to nextgen_engg
Here is one approach, the simplest and not much appealing:

int main()
{
string str;
char ch;
FILE *fp;
fp = fopen("<filename>","rb"); //Here enter
appropriate filename which you want to read.
ch = fgetc(fp);
do
{
str += ch;
ch = fgetc(fp);
}while(ch != EOF);
cout << str;
return 0;
}

Please comment! For the mean time, looking for better ideas.

Mickey

unread,
May 15, 2010, 10:04:43 PM5/15/10
to nextgen_engg
This is what I also came up with but I am satisfied and am thinking if
there can be any better solution.

Two suggestions in your code: 1. always check for the return value of
fopen. 2. What happens in your code when it is a zero byte file?

Regards,
Jyoti

Mickey

unread,
May 15, 2010, 10:11:06 PM5/15/10
to nextgen_engg
*not satisfied
Message has been deleted

Nilu

unread,
May 17, 2010, 7:18:22 AM5/17/10
to nextgen_engg
don't know if it is the right way:
http://codepad.org/soG6ITTB

Regards,
Nilesh
> > > > Jyoti- Hide quoted text -
>
> - Show quoted text -

Nilu

unread,
Mar 23, 2012, 12:42:17 PM3/23/12
to nextge...@googlegroups.com
another way to read a file in a string :

std::string read(const std::string& filename)
{
std::ifstream ifs(filename.c_str());

typedef std::istreambuf_iterator<char> charStreamBuf_iter;

return std::string(charStreamBuf_iter(ifs.rdbuf()), charStreamBuf_iter());
Reply all
Reply to author
Forward
0 new messages