Monday, December 16, 2013

How to read file content with out using readline in C++!!

Below is the simple c++ program to read the whole content from file with out using readline function. The idea is, get the size of the file by moving the seek position to the end of the file and allocate the buffer space for the size and read the file content using read function into the allocated buffer.

#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
 ifstream filenumbers;"numbers.txt");
 int length;
 //checks if input file is accessible
 if (!filenumbers) 
  cout << "The input file will not open. Please restart." << endl;

 // move the position to end of the file
 filenumbers.seekg(0, std::ios::end);    
 // get the current position(now it is at the end of the file so length of the content)
 length = filenumbers.tellg();           
 // move the position to start of the file 
 //(coming back to start of the file)
 filenumbers.seekg(0, std::ios::beg);
 // allocate memory for a buffer of file size   
 char *buffer = new char[length];  
 // read whole content of the file into the buffer, length);       
 cout<<"buffer is \n"<<buffer;
 return 0;


buffer is
11 2 3 4 5

Popular Posts