#include#include using namespace std; int main () { ifstream file("example.txt"); // get length of file file.seekg (0, file.end); int length = file.tellg(); file.seekg (0, file.beg); // read file contents char * buffer = new char [length]; file.read (buffer,length); // display file contents cout.write (buffer,length); cout << endl; // get current position of pointer int pos = file.tellg(); cout << "Current file pointer position: " << pos << endl; // close file file.close(); return 0; }
#includeIn this example, we open a file and determine its size using the tellg() function. We then allocate memory for the file contents and read them into a buffer. We print the contents of the buffer to the console. Package/library: Standard C++ Library (fstream)#include using namespace std; int main () { ifstream file("example.txt"); // get file size file.seekg (0, file.end); int fileSize = file.tellg(); file.seekg (0, file.beg); // allocate memory for file contents char* buffer = new char[fileSize + 1]; buffer[fileSize] = '\0'; // read file contents file.read(buffer, fileSize); // display contents to console cout << "File contents: " << endl << buffer << endl; // close file file.close(); return 0; }