Advertisement

reading a file

Started by August 26, 2000 11:45 AM
2 comments, last by FrigidHelix 24 years, 4 months ago
This is a basic question: Using the fstream classes, what code would be required to do the following: Find the length of the file in bytes Allocate space for a buffer of type "char[]" Read an entire file''s contents into the buffer I have mostly used the file reading functions from "stdio.h", and am unfamiliar how this would be done with the C++ equivalent.
I suppose you could do it like this:

fstream stream( "file.dat",ios::in );

stream.seekg( 0,ios::beg );
int startPos=stream.tellg()
stream.seekg( 0,ios::end );
int endPos=stream.tellg();
int size=endPos-startPos;

char* buffer=new char[size];
if(buffer==NULL)
...handle error...

stream.seekg( 0,ios::beg );
stream.read( buffer,size );

That should work. There are two file pointers in the iostream classes, the "get" pointer and the "put" pointer. The seekg and tellg methods modify the get pointer, if you needed to do this when writing a file, use seekp and tellp.

Hope that helps.

-Liquid
Advertisement
excellent, that is just what i was looking for.
quote:
stream.seekg( 0,ios::beg );
int startPos=stream.tellg()


Won't these lines of code always set 'startPos' to zero?

//Gaijin

Edited by - Gaijin on August 26, 2000 4:05:18 PM
// Gaijin"There is only one way to find out if a man is honest...ask him. If he says yes, you know he is crooked." -- Groucho Marx"Sex isn't the answer. Sex is the question. 'Yes' is the answer" -- Unknown

This topic is closed to new replies.

Advertisement