Jump to content
  • Advertisement
Sign in to follow this  
philipptr

c++ reading File into ram

This topic is 4590 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Since I started to write a little Emulator, I tried to read a file into ram. At the moment im using fstream which doesn really work, since I cant find a way to Import the whole file into one char[]. When I use getline it always stops between 0x12 and 0x1A. Isnt 0x0D0A a linebreak? And also it doesnt work when im using a delimiter different from \n. Does someone now a good library for file access with which I can read a complete file exactly the way it is on disk into a char[]?

Share this post


Link to post
Share on other sites
Advertisement

This should get you going:


bool cFileMem::open (const char* filename)
{
close();
FILE* f;

if ((f = fopen(filename, "rb")))
{
fname = filename;

// determine filesize and go back to filestart
U32 filelen=0;
fseek(f,0,SEEK_END);
filelen=ftell(f);
fseek(f,0,SEEK_SET);

U32 bytesRead = 0;
if (filelen!=0)
{
// allocate memory and read the entire file
buf.resize (filelen);
bytesRead = fread( &buf[0], sizeof(U8), filelen, f );
}
fclose (f);
return (bytesRead==filelen);
}
else
{ return false;
}
}


Share this post


Link to post
Share on other sites
std::ifstream file("file.bin", std::ios_base::binary | std::ios_base::ate | std::ios_base::in); 
int filesize = file.tellg();
char* buffer = new char[filesize];
file.seekg(0, std::ios_base::beg);
file.read(buffer, filesize);
file.close();

Share this post


Link to post
Share on other sites
thanks for the help, works now.
I think its strange that the std lib provides so many functions which do things like stop at \n and in the end only confuse, instead of just giving one way you to get a single char[] and then split it at \n. atleast it works now :)

Share this post


Link to post
Share on other sites
Those are useful when you need to parse text files. You should never use the text functions for binary or the binary functions for text.

Share this post


Link to post
Share on other sites
IMO getline is just for that designed - to read line, and stop at EOL (end-of-line - 0x0A or 0x0D) or EOF (end-of-file - 0x1A).
If your file isn't text file, but is binary file, then don't use such methods. Open file in binary mode (ios_base::binary or "b") and read whole file, or in blocks, not line by line!

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!