Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Not C++,but couldn't find a C forum ;)

Status
Not open for further replies.

weevilofdoom

Programmer
Jan 28, 2003
91
US
how would one check for an empty file in C?

The file exists, but it has no data in it, so when I
try to read from the file, boom, you know? ;)
And I don't want to stick data in the file, I want
to be able to check for empty files. The weevil of doooooooooom
-The eagle may soar, but the weasel never gets sucked up by a jet engine (Anonymous)
 
Not much help for an answer, but maybe a redirect for the question: forum205 open it, check if you're already at eof. Not sure if it works, but it's a theory. ----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
If the length of the file is zero then it's empty
tellis.gif

[sup]programmer (prog'ram'er), n A hot-headed, anorak wearing, pimple-faced computer geek.[/sup]​
 
******************************************************************
Here is how you can do it:
Code:
.......
.....

// find the size of a file
int filesize( char *filename )
{
   long fsize = 0;
   FILE *file;
   char c; 

   file = fopen(filename,"r");
   if(!file) // if failiure
   {
      fprintf( stderr,"error while opening %s.\n",filename );
      return -1;
   }

   while((c = getc(file)) && !feof(file))
   {
      fsize++;
   }

   fclose(file);
   return fsize;
}

....
...

char *filename = "myfile.txt";

if( !filesize(filename))
{
   cout<<&quot;This file is empty.&quot;<<endl;
}
....
[\code]
 
Leibnitz:

Thank you, exactly what I was looking for :) The weevil of doooooooooom
-The eagle may soar, but the weasel never gets sucked up by a jet engine (Anonymous)
 
int file_handle;
long file_length;

file_handle = _open(&quot;your_file.typ&quot;, _O_BINARY | _O_RDONLY);
if(file_handle==(-1)) process_error();
else
{
file_length=_filelength(file_handle);
_close(file_handle);
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top