File reading in c++

File reading in c++

Page 1 of 1

1 Replies - 2153 Views - Last Post: 02 November 2007 - 08:06 PM Rate Topic: -----

#1 prads   User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 113
  • Joined: 22-October 07

File reading in c++

Post icon  Posted 02 November 2007 - 07:08 PM

Hello,
The C++ pgm below opens a file, reads it and displays what is read. However at the end of the output it also appends some crazy looking characters. Pls correct it for me.
Thanks,
Prads
#include <iostream>
#include <cstdio>
#include <cstdlib>

using namespace std;
int main ()
{
FILE * pFile;
long lSize;
char * buffer;
size_t result;

pFile = fopen ( "C:\\t1.txt" , "rb" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);

// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize);
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
if (result != lSize) {fputs ("Reading error",stderr); exit (3);}

/* the whole file is now loaded in the memory buffer. */

// terminate
cout<<buffer<<endl; //check this
fclose (pFile);
free (buffer);
getchar();
return 0;
}


Also if I want to move the starting point from the beginning of file offset by 5, if i use the following, will it work....
fseek(pFile,5,SEEK_SET);

Is This A Good Question/Topic? 0
  • +

Replies To: File reading in c++

#2 baavgai   User is online

  • Dreaming Coder
  • member icon


Reputation: 7183
  • View blog
  • Posts: 14,970
  • Joined: 16-October 07

Re: File reading in c++

Posted 02 November 2007 - 08:06 PM

LOL, this looks real familiar: http://www.cplusplus...tdio/fread.html :P

On the fopen, try "r", rather than "rb".

Also, since it looks lifted, it's a poor example. You'd might do better with fstream, though this one seem better done.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1