Read from file; Store contents in char stream

I haven't done any experimenting with C++ file manipulation and I am revising it now.
I know that to read lines from a file, I can do this:

1
2
3
4
5
6
    string contents;
    if (file.is_open())
    {
        while(!file.eof())
        getline(file, contents);
    }


Now, I am having some problem thinking of a way to use char stream instead of a string.

I can either first take input in string and then convert it to a char stream. But that is not very subtle.

I can check the size of file (I don't know how to do that). It should give me some value in bytes. One char = 1B, so I get to create an array of of the size it returns me. Once I do that, I can pick contents char-by-char (I don't know how to do that either). And afterwards, append the char stream by a delimiting character like '\0' or something like that.

Any help will be duly appreciated.
Hi,

This following code loads a file into memory and prints it.
But it shows how to get the filesize of a ifstream file, how to allocate memory and read file.

The get filesize stuff is a bit messy but that is how it says to do it in the reference section
of this site.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <fstream>

using	namespace	std;

int	main(int argc,char** argv)
{
	ifstream	file;
	int		size;
	char*	inBuf;

	file.open("calc.cpp",ios_base::binary);

	if (file.is_open())
	{
		file.seekg(0,ios::end);		//get file size
		size = file.tellg();            //
		file.seekg(0,ios::beg);         //

		inBuf = new char[size];

		file.read(inBuf,size);
		file.close();
	}

	cout <<inBuf;
}


Hope this helps you
Shredded
Topic archived. No new replies allowed.