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.
Output:
buffer is
10
20
30
40
11 2 3 4 5
#include <iostream> #include <fstream> #include <iomanip> using namespace std; int main() { ifstream filenumbers; filenumbers.open("numbers.txt"); int length; //checks if input file is accessible if (!filenumbers) { cout << "The input file will not open. Please restart." << endl; exit(1); } // 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 filenumbers.read(buffer, length); cout<<"buffer is \n"<<buffer; filenumbers.close(); return 0; }
Output:
buffer is
10
20
30
40
11 2 3 4 5
No comments:
Post a Comment