Measuring file size in C++ using fstream
In my task, I needed to check the file size by searching on the forumal collected the function is_Empty
, but it turns out that after checking the file size, I can't read it normally. I read from the file using fin >>
in the while loop using eof, eof reads normally, i.e. the loop works, but I don't get any data from the file.
Where can the error be hiding?
bool is_Empty(const char*name)
{
fstream fi; fi.open(name);
long file_size;
fi.seekg(0, ios::end);
file_size = fi.tellg();
fi.close();
if (file_size == 0)
return true;
else
return false;
}
void read(const char *namefile)
{
int i(0);
if (is_Empty(namefile))
{
cout << "Pust"; return;
}
ifstream fin;
fin.open(namefile);
while(!fin.eof()){
//Тут дальше идёт код считывания из файла
2 answers
The operation of opening/closing a file is quite expensive, it is better to do without it:
bool isEmpty( std::ifstream &f )
{
char c;
f >> c;
if( !f ) return true;
f.seekg( 0, ios::beg );
return false;
}
void read( const char *namefile)
{
int i(0);
std::ifstream fin( namefile );
if( isEmpty( fin ) ) {
cout << "Pust";
return;
}
while(!fin.eof()){ ...
Two things. If you know the file name immediately, then it is better to initialize the std::ifstream
object immediately, rather than call open()
separately. Second, judging by while( !fine.eof() )
, your reading is also not all right. Details can be found here - Why is it considered wrong to write while (!input_stream.eof())?
You can count the number of characters in the file, and since one character is equal to one byte, it is not difficult to write such code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
size_t ByteOfFile(const string path){
ifstream file(path.c_str()); // файл
size_t s = 0; // счетчик символов
while (!file.eof()) { // пока не достигнут конец файлв
file.get(); // читать по одному символу
s++; // и увеличивать счетчик
}
file.close(); // обязательно закрыть
s--; // убираем лишнюю итерацию
return s; // вернуть число символов/байтов
}
int main(){
cout << "file size " << ByteOfFile("C:\\test.txt") << " bytes" << endl;
return 0;
}
File test.txt :
123
456
789
Conclusion: