Home c++ Measuring file size in C++ using fstream

Measuring file size in C++ using fstream

Author

Date

Category

In my task, I needed to check the file size, having searched the forum, I collected the is_Empty function, but it turns out that after checking the file size I cannot read it normally. I read from a file using fin & gt; & gt; in a while loop using eof, eof reads fine, i.e. the loop works, but I don’t get any data from the file.
Where could 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 & lt; & lt; "Pust"; return;
  }
  ifstream fin;
  fin.open (namefile);
while (! fin.eof ()) {
// Here comes the code for reading from the file

Answer 1, authority 100%

The operation of opening / closing a file is quite expensive, it is better to do without it:

bool isEmpty (std :: ifstream & amp; f)
{
  char c;
  f & gt; & gt; 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 & lt; & lt; "Pust";
    return;
  }
  while (! fin.eof ()) {...

Two points. If you know the file name right away, then it is better to initialize the std :: ifstream object right away, rather than call open () separately. Second, judging by while (! Fine.eof ()) reading is not all right for you either. Details can be found here – Why is it considered wrong to write while (! Input_stream.eof ())?


Answer 2

You can read the number of characters in the file, and since one character is equal to one byte, it is easy to write a similar code:

# include & lt; iostream & gt;
#include & lt; fstream & gt;
#include & lt; string & gt;
using namespace std;
size_t ByteOfFile (const string path) {
  ifstream file (path.c_str ()); // file
  size_t s = 0; // character counter
  while (! file.eof ()) {// until the end of the file is reached
    file.get (); // read one character at a time
    s ++; // and increment the counter
  }
  file.close (); // be sure to close
  s--; // remove unnecessary iteration
  return s; // return the number of characters / bytes
}
int main () {
  cout & lt; & lt; "file size" & lt; & lt; ByteOfFile ("C: \\ test.txt") & lt; & lt; "bytes" & lt; & lt; endl;
  return 0;
}

file test.txt :

123
456
789

output:

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions