Search code examples
c++fstream

Find size of binary file, function tellg() returns -1


I've written a function which initialize some fields of FileDataTransfer object and also finds size of file.

Here is a code:

bool FileTransferData::initialize(const string& fileName, string& errMsg)
{
   if (this->transferInProgress)
   {
       errMsg = "\nFile Transfer already in progress. File Transfer Request denied.\a";
       return false;
   }
   this->inFileStream.open(fileName, ios::binary | ios::ate);
   if (!inFileStream.is_open())
   {
       errMsg = "\nRequested file: " + fileName + " does not exist or was not found.\a";
       return false;
   }
   this->fileName = fileName;
   this->fileSize = (int)this->inFileStream.tellg();
   this->inFileStream.seekg(0);
   this->fileOffset = 0;
   this->transferInProgress = true;
   return true;
}

But field this->fileSize become -1 after completion of my function, I think tellg() returns -1, but why ?


Solution

  • You can get the size of a file like this

    long long filesize(const char *fname)
    {
       int ch;
       FILE *fp;
       long long answer = 0;
       fp = fopen(fname, "rb");
       if(!fp)
         return -1;
       while( (ch = fgetc(fp)) != EOF)
          answer++;
       fclose(fp);
       return answer;
    }
    

    It's portable, and whilst it does a pass over the file, usually you'll have to pass through the file anyway, so you're not blowing up the big O efficiency of your function. Plus fgetc() is highly optimised for buffering.