Monday, May 24, 2010

In c++, how do I check if file length is zero?

I am doing a quiz project for the school exam. I have to check if file length of a file is zero ( concept of files). Can I use tellg() ?


I am implementing it in a class .Then I use if() statement to check if file length of a file which stores the quiz questions is zero( i.e there are no questions). If it is zero Then I invoke another function asking the user to input questions first.


Here should i use tellg() to check if there are no questions in the file.








P.s: I don't want it to be too complex...as I've been learning c++ only from june 2006

In c++, how do I check if file length is zero?
This page seems to have what you want.
Reply:May be my blog helps you. I have some code related to file handling in C++ at http://codesbyshariq.blogspot.com
Reply:you can use fstat to check if a file exists. it returns -1 if the file does not exist.





this function also exists on windows.
Reply:Use this method:





======================================...


#include %26lt;fstream%26gt;


int FileSize(const char* sFileName)


{


std::ifstream f;


f.open(sFileName, std::ios_base::binary | std::ios_base::in);


if (!f.good() || f.eof() || !f.is_open()) { return 0; }


f.seekg(0, std::ios_base::beg);


std::ifstream::pos_type begin_pos = f.tellg();


f.seekg(0, std::ios_base::end);


return static_cast%26lt;int%26gt;(f.tellg() - begin_pos);


}


======================================...





Drawback: If the file size is bigger than what int can hold, this method won't work, but in your case, you will be using it to check whether file size is 0, so it will work fine.








If you want to eliminate the limitation of int datatype, and if you are using Visual C++ compiler, then you can use the following function:





======================================...


#include %26lt;sys\types.h%26gt;


#include %26lt;sys\stat.h%26gt;


__int64 FileSize64( const char * szFileName )


{


struct __stat64 fileStat;


int err = _stat64( szFileName, %26amp;fileStat );


if (0 != err) return 0;


return fileStat.st_size;


}


======================================...


No comments:

Post a Comment