Advertisement

Reading files with STL

Started by March 10, 2001 02:58 PM
3 comments, last by Imois 23 years, 10 months ago
I'm trying to read the contents of a .tga file and storing it in a buffer. I want to do this with the Standard Library but I'm having some problems.
    
// Load a texture

CTgaTextureLoader	tgafile;
char*		pBuffer;
ifstream	fFile("background-32bit.tga");
int			nSizeofFile	= 0; // ??? how do I get the filesize ?


// Allocate a buffer

pBuffer = new char[nSizeofFile];

// Copy file to buffer (how?)



// tgafile.Load(pBuffer,nSizeofFile)

    
My questions are: 1) How do I open a file for binary input. 2) How do I read a file. 3) How do I determine the file size. Thanks. Edited by - Imois on March 10, 2001 4:00:24 PM
You should look at the documentation for basic_istream. ifstream inherits from istream, and the only thing it adds are basically the open, close and isopen methods; all of the questions you''re asking are related to istream, not ifstream.

1) The file is already open, and you can alternate between formatted (non-binary) or non-formatted (binary) input with each call to the class.

2) Use operator >> for formatted input, and the read function for unformatted.

For example, to read 200 characters into the array char buf[200]:
fFile.read (buf, 200);

3) It''s a little tricky. The stream keeps an count of har far it is into the file; you set this count by the "seekg" function, and you read it with the "tellg". When you open the file, the count is zero (at the beginning of the file). To tell what the filesize is right after you open, do this:
fFile.seekg (0, ios_base::end); // seek 0 from end of file
int fileSize = fFile.tellg (); // tell position = filesize
fFile.seekg (0, ios_base::beg); // go back to beginning of file

tellg () techincally returns a basic_ios::pos_type, which is a structure with 4 members, one of which is the size. However, it has an implicit conversion operator to int, so this will work.

If you try to do this after reading anything from the file, it will reset your file to the beginning, so take care.

Advertisement
Thanks for the quick reply.

I will try it. Looks promising.
Here's what I had to do in my college CS class.

  ifstream fin("myfile.tga");vector<char> my_array;copy(istream_iterator<char>(fin), istream_iterator<char>(), back_inserter(my_array));  


It'll probably work with an array, since it works basically the same, but I haven't tried it. I'm for sure it will work with the STL vector though.

Email rreagan@mail.utexas.edu if you have anymore questions about this. The Class I'm taking right now is about writing all of these data structures like vector, list, etc. and using the STL with them.



Edited by - merge2 on March 11, 2001 5:03:37 AM
Stoffel - it worked
Merge2 - ha! looks advanced! might try it.

This topic is closed to new replies.

Advertisement