-1

I am reading data from a comma delimited csv file. I would like to verify that the file has data before reading and return an error if the file doesn't have any data.

const char* sample_data_file = "sample_data1.csv" ; std::ifstream file(sample_data_file);

Thanks!

Steve
  • 27
  • 2
  • 3
    Possible duplicate of [Checking for an empty file in C++](http://stackoverflow.com/questions/2390912/checking-for-an-empty-file-in-c) – sashoalm Nov 25 '16 at 22:49
  • I tried that, didn't work. std::ifstream file(sample_data_file); if(file.peek() == std::ifstream::traits_type::eof()) cout<<"empty file"< – Steve Nov 25 '16 at 22:56

2 Answers2

1

A simple call to stat will tell you if the file is empty. That should be enough to solve your problem.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
0

check the size of the file when you open it?

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main ()
{

  ifstream myfile ("C:/temp/sample1.csv");

  // this gives you the number of bytes in the file.

  if (myfile.is_open())
  {
      long begin, end;

      begin = myfile.tellg();
      myfile.seekg (0, ios::end);
      end = myfile.tellg();

      if(end-begin == 0)
      {
          cout << "file is empty \n";

      }
      else
      {
        cout << "size: " << (end-begin) << " bytes." << endl;
      }

      myfile.close();

  }

  else cout << "Unable to open file \n";

  return 0;
}
agent_bean
  • 1,493
  • 1
  • 16
  • 30