UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » C++
  • » reading a text file in c++

#1 2009-05-26 05:15 AM

vishy_85
Member
Registered: 2009-02-10
Posts: 3

Re: reading a text file in c++

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

Offline

#2 2009-05-26 07:43 AM

yurec
Member
From: Singapore
Registered: 2006-11-16
Posts: 134

Re: reading a text file in c++

Probably you'd moved the file "vishy.txt" somewhere. And it can't be opened.
Consider this :

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


int main () {

  const char * file_name = "vishy.txt";
  
  std::ifstream file(file_name ,std::ios::in);
  if (!file.is_open())
    {
    std::cout << "can't open file" << file_name << std::endl;
    return -1;
    }
    
  std::string file_content;
  file >> file_content;
  std::cout << file_content.c_str();
  
  return 0;
  }

Offline

  • Index
  • » C++
  • » reading a text file in c++

Board footer

Powered by FluxBB