Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 131,739 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,183 people online right now. Registration is fast and FREE... Join Now!




File reading issues

 
Reply to this topicStart new topic

File reading issues

microchip
post 9 Dec, 2005 - 02:23 PM
Post #1


New D.I.C Head

*
Joined: 14 Aug, 2005
Posts: 37



Thanked 3 times
My Contributions


I've been having trouble reading text files for some time now. So now I've got a few questions:

I use this code to load a textfile to RAM:
CODE

   cout << "Reading file to RAM..." << endl;
   inputFile.seekg(0, ios::end);
   unsigned int fileLength = inputFile.tellg();
   inputFile.seekg(0, ios::beg);
   char *fileData = (char*) malloc(fileLength);
   if (fileData == NULL) {
       cerr << "Not enough memory availble..." << endl
            << "Press ENTER to exit...";
       cin.get();
       return 0;
   }
   inputFile.read(fileData, fileLength);
   inputFile.close();


I find get the length of the file by setting the file pointer to the end, and then read at what position it is. This will return the number of characters in the file. Then I allocate that size to the char* fileData and save the contents of the file to that piece of RAM.

The only trouble I'm having is that the length of fileData as a string is different than fileLength (the number of characters in the file). The rest of the array is filled with zero's.
Why is this? Isn't each character in the file copied into the array?

And what's the deal with newlines? Windows saves a newline as CR NL, Unix as NL and MacOS as CR. How is handled by C++?
User is offlineProfile CardPM

Go to the top of the page

Nova Dragoon
post 13 Dec, 2005 - 11:35 PM
Post #2


The Innocent Shall Suffer, Big Time

Group Icon
Joined: 16 Aug, 2001
Posts: 6,126



Thanked 4 times

Dream Kudos: 515

Expert In: Python, Linux

My Contributions


A problem you maybe seeing here is that in initializing *fileData, you are setting the size to fileLength which is the number of bytes the file is, however I think with malloc (has been ages since I used it last) needs the size differently such as

Malloc(fileLength * sizeof(char) )
User is online!Profile CardPM

Go to the top of the page

microchip
post 14 Dec, 2005 - 07:45 AM
Post #3


New D.I.C Head

*
Joined: 14 Aug, 2005
Posts: 37



Thanked 3 times
My Contributions


I thought sizeof (char) is 1. But you're right. It's a nicer habit to do what you proposed.

I still think it's wierd though...
User is offlineProfile CardPM

Go to the top of the page

Reply to this topicStart new topic
Time is now: 11/20/08 10:59AM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month