Skip to main content
GameDev.net gamedev.net
🔒 Locked

c++ reading File into ram

Started by ........................................ Apr 20, 2006 at 4:42 PM 4 replies 4.2k views
Original Post
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[]?
Kitt3n
Kitt3n

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;   }}

visit my website at www.kalmiya.com
bubu LV
bubu LV
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();
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 :)
Simian Man
Simian Man
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.
bubu LV
bubu LV
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!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.