- 1). Open a file in the C++ code. See this skeleton code as an example:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ifstream file;
file.open("filename.txt");
if(!file.is_open()){
cout << "File Not Open" << endl;
return 0;
}
}
This basic code creates an "ifstream" object "file" which serves as an input stream for the file. Then, the "if" statement checks if the file opened successfully. If it does not, any operation on the ifstream object will throw an error. - 2). Navigate through the file using the internal file pointers. Programmers moves these pointers through the "tellg()" and "seekg()" functions. The tellg() function returns the position of the pointer in the file as an integer:
int location = file.tellg();
The seekg() function actually moves the pointer, either based on an absolute location, or based on another location, including an offset:
file.seekg(5); //moves pointer to absolute location
file.seekg(4, ios::beg); //moves pointer four places from the beginning of file - 3). Read the size of the file using the file pointers. Putting all the examples together, the file functions in the ifstream object will get the starting position, then move the pointer to the end and retrieve the ending position. The difference of these positions is the file size in bytes.
int start = file.tellg();
file.seekg(0, ios::end);
int end = file.tellg();
int size = (end - start);
SHARE