hello all ,
im trying to read a text file and display its contents. While i got the code running and the output was displayed perfectly for sometime , i started getting Abort(core dump) error . Am i missing something here ? im using HP-UX.

#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include <string.h>



int main () {
  int length;
  char* buff=NULL;

  ifstream is;
  is.open ("vishy.txt", ios::in );

  // get length of file:
  is.seekg (0, ios::end);
  length = is.tellg();
  is.seekg (0, ios::beg);

  // allocate memory:

  buff = new char [length];
  // read data as a block:
  is.read (buff,length);
  is.close();

  cout.write (buff,length);
  delete[] buff;
  buff = NULL;
 
}

thanks
vishy

Recommended Answers

All 7 Replies

The most likely cause, and you haven't got a check for it, is that the file does not exist in the specified path. That will cause the error you are seeing.

With any particular text file?
Or very large text files?

Use a debugger to tell you which line the abort comes from, and try to infer some reasons for getting into that state.

Because you don't check your new array actually succeeded.

Besides, reading the WHOLE file into memory in one block is pretty wasteful for large files.

the core dump ocurs while trying to allocate memory
// allocate memory:

buff = new char [length];

hey , i gave the wrong file path , thanks it works now

i got one more query ... is it possible to store the contents of the file in a vector ? if so , how do i copy the contents of the file to the vector ???

thanks

the value of length is

length = is.tellg();

the pointer returns the location...

the value of length is

length = is.tellg();

the pointer returns the location...

Yep, gdb showed me the error was on the buffer allocation and that the reason was that a valid length could not be determined since the file was not specified. Throw in a check for that.

As for storing the file in a vector, how would you want to do it?
A vector contains objects - for example a vector of strings - so would you want to have one string per line and store each line in a vector?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.