English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

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

2007-10-24 01:17:48 · 4 answers · asked by Anonymous in Computers & Internet Programming & Design

4 answers

This page seems to have what you want.

2007-10-24 01:34:06 · answer #1 · answered by AnalProgrammer 7 · 0 0

Use this method:

=========================================
#include
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(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
#include
__int64 FileSize64( const char * szFileName )
{
struct __stat64 fileStat;
int err = _stat64( szFileName, &fileStat );
if (0 != err) return 0;
return fileStat.st_size;
}
=========================================

2007-10-24 04:56:20 · answer #2 · answered by Koushik Biswas 3 · 0 0

May be my blog helps you. I have some code related to file handling in C++ at http://codesbyshariq.blogspot.com

2007-10-24 02:07:25 · answer #3 · answered by Shariq (http://coinsindia.info) 5 · 0 0

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.

2007-10-24 02:14:36 · answer #4 · answered by cruppstahl 4 · 0 0

fedest.com, questions and answers