473,749 Members | 2,463 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How do I check if a file is empty in C??

Hi group..I am writing a playlist management protocol where I have a
file that holds all the playlists and a file that holds all the
songs....before a playlist is created I need to check to see if the
playlist file is empty so that I can assign an integer value to a
playlist id field if it is the first playlist being written to the
file....can anyone help?? Thanks in advance

wetherbean

Nov 14 '05 #1
19 32327
Nevermind, someone just gave me an idea that I think will work
fine...he said to fseek tot he end of the file and then do an ftell and
if it is 0 then the file is empty

Nov 14 '05 #2
In article <11************ *********@o13g2 000cwo.googlegr oups.com>
wetherbean <bj******@gmail .com> wrote:
Hi group..I am writing a playlist management protocol where I have a
file that holds all the playlists and a file that holds all the
songs....befor e a playlist is created I need to check to see if the
playlist file is empty so that I can assign an integer value to a
playlist id field if it is the first playlist being written to the
file....can anyone help?? Thanks in advance


Definition: a file is "empty" if you cannot read anything from it.
(Is there a potential flaw in this definition? [I say yes, but
this is an exercise; you are supposed to identify potential flaws,
not just answer "yes" or "no". :-) ])

Conclusion: open the file and try to read from it. If you get
some data, it is not empty. If you get EOF immediately, it is
empty.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #3
wetherbean wrote:
Nevermind, someone just gave me an idea that I think will work
fine...he said to fseek tot he end of the file and then do an ftell and
if it is 0 then the file is empty


Alternatively, if you want to avoid actually having to open each file,
until you're confident that it's non-empty, then you could use stat().
As an example, check out the code below.

One caveat, if you use stat(), you'll find out the size of the file at
the time of the stat() call. So, in principle, it's possible for the
file to get truncated or deleted before you actually open it up and do
anything with it.

-Dan

get_file_size.c
----------------------------------------------------------
#include <stdio.h>
#include <sys/stat.h>

int main(int argc, char *argv[]) {
int i;

if (argc == 1) {
fprintf(stderr, "Usage:\n\t %s (file1) (file2) .....\n", argv[0]);
return -1;
}

for (i = 1; i < argc; i++) {
struct stat stat_record;
printf("%s - ", argv[i]);
if (stat(argv[i], &stat_record ))
printf("Can't stat (does file exist?)\n");
else if (!stat_record.s t_size) printf("Empty file\n");
else {
/* Now you can open up the file an do what ever it is your going
to do - since it is non-empty
(or more technically correct probably still non-empty) */
printf(" Non-empty file (%d bytes)\n", stat_record.st_ size);
}
}
return 0;
}
----------------------------------------------------------

Nov 14 '05 #4
"wetherbean " <bj******@gmail .com> wrote:
# Nevermind, someone just gave me an idea that I think will work
# fine...he said to fseek tot he end of the file and then do an ftell and
# if it is 0 then the file is empty

The return value of ftell is not guarenteed to be meaningful except to fseek.
It might be a file length, or something else altogether.

In ANSI C, open the file and see if you can read anything before getting an EOF.
Your system might provide other calls that don't require openning the file.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
What kind of convenience store do you run here?
Nov 14 '05 #5
On Sat, 23 Apr 2005 16:39:39 -0600, Daniel Cer wrote:
wetherbean wrote:
Nevermind, someone just gave me an idea that I think will work
fine...he said to fseek tot he end of the file and then do an ftell and
if it is 0 then the file is empty


Alternatively, if you want to avoid actually having to open each file,
until you're confident that it's non-empty, then you could use stat().


There is no function called stat in Standard C which is what is discussed
here.

Rob Gamble
Nov 14 '05 #6
SM Ryan <wy*****@tang o-sierra-oscar-foxtrot-tango.fake.org> writes:
"wetherbean " <bj******@gmail .com> wrote:
Nevermind, someone just gave me an idea that I think will work
fine...he said to fseek tot he end of the file and then do an ftell and
if it is 0 then the file is empty


The return value of ftell is not guarenteed to be meaningful except
to fseek. It might be a file length, or something else altogether.


[Quote character '#' changed to '>' as usual.]

Actually, the result of ftell() is meaningful if the file is opened
in binary mode.

C99 7.19.9.4p2:

The ftell function obtains the current value of the file position
indicator for the stream pointed to by stream. For a binary
stream, the value is the number of characters from the beginning
of the file. For a text stream, its file position indicator
contains unspecified information,
[snip]

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #7
On Sun, 24 Apr 2005 00:35:26 GMT, Keith Thompson <ks***@mib.or g> wrote
in comp.lang.c:
SM Ryan <wy*****@tang o-sierra-oscar-foxtrot-tango.fake.org> writes:
"wetherbean " <bj******@gmail .com> wrote:
Nevermind, someone just gave me an idea that I think will work
fine...he said to fseek tot he end of the file and then do an ftell and
if it is 0 then the file is empty


The return value of ftell is not guarenteed to be meaningful except
to fseek. It might be a file length, or something else altogether.


[Quote character '#' changed to '>' as usual.]

Actually, the result of ftell() is meaningful if the file is opened
in binary mode.

C99 7.19.9.4p2:

The ftell function obtains the current value of the file position
indicator for the stream pointed to by stream. For a binary
stream, the value is the number of characters from the beginning
of the file. For a text stream, its file position indicator
contains unspecified information,
[snip]


The ftell() function is indeed meaningful for binary files, but using
fseek() first to get to the end, so ftell() can return the file size,
it not.

7.19.9.2 P3:

A binary stream need not meaningfully support fseek calls with a
whence value of SEEK_END.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #8
Robert Gamble wrote:

There is no function called stat in Standard C which is what is discussed
here.

Rob Gamble


Even though stat() is not part of the current C standard, it is
available to C developers, in some form or another, on most of the
systems they might target. For example, the code should work as is on
systems like Linux, Mac OS X, Solaris, and perhaps even OpenVMS.

Even on Microsoft Windows, I think the only change would be to use
_stat() rather than stat(), with this function still being included from
the same header file, sys/stat.h. Moreover, the structure populated by
_stat() still contains a field 'st_size' that indicates the size of the
file in question and returns 0 on success or a non-zero value on failure.

Anyhow, using stat(), or a stat like function, should be a more
efficient than having to open each file and then attempting to read from
it to see if it contains any data. And, it seems a bit more elegant.
But, yeah, I probably should have said something about it being part of
the POSIX standard and/or system dependent rather than being Standard C.

-Dan

Nov 14 '05 #9
>Robert Gamble wrote:
There is no function called stat in Standard C which is what is discussed
here.

In article <42************ **@gmail.com>
Daniel Cer <Da********@gma il.com> wrote:Even though stat() is not part of the current C standard, it is
available to C developers, in some form or another, on most of the
systems they might target.
Perhaps. It is certainly available in all POSIX-conformant systems.
Still, "available in most systems" is obviously not quite as good
as "available in all systems on which files are available".
Anyhow, using stat(), or a stat like function, should be a more
efficient than having to open each file and then attempting to read from
it to see if it contains any data.


Have you tested this? In particular, have you compared the
performance of the sequence:

stat the file to find out if it is empty.
then, open the file and if it was empty earlier, write an ID, but if it
was not empty, read the ID;
then, write any data;
finally, close the file.

vs:

open the file;
try to read the ID; if none available, write an ID;
then, write any data;
finally, close the file.

? Try it (with a large number of files) and see if you get the
results that *I* expect, namely, that the latter should be slightly
faster. (How much faster depends on the system. The reason is
that, on modern systems, "look up file by name" happens to be the
slowest file-related operation the system ever does. The "stat
then open" sequence looks up the file name twice. The "open then
manipulate" sequence looks up the file name just once. You can
achieve the same performance as the "test read" method by using
fstat() once the file is open, of course, if you are on a POSIX
system.)

Of course, the "best" way to open the file is often to use the
non-C-Standard function that says "open this file for reading and
writing, creating it if necessary, but not discarding existing
data". Standard C has only three ways to open for both reading
and writing:

method1 = fopen(filename1 , "r+"); /* or r+b */
method2 = fopen(filename2 , "w+"); /* or w+b */
method3 = fopen(filename2 , "a+"); /* or a+b */

The file opened via method 1 must already exist -- if not, the
fopen() must fail and method1 will be NULL. Method 2 will create
the file, but an existing file opened via method 2 has any existing
data removed first, which is clearly not what is wanted in this
case. Method 3 will also create the file if it does not yet exist,
but has the drawback that *every* write to the file will append,
whether or not you positioned the file elsewhere with fseek().
If this is what you wanted, great, but if not -- well, there
really ought to be a variation on "r+" meaning "create file if
needed". Perhaps "r+c", or perhaps "R+" or "c+", for instance.

(If you have a POSIX system, you can use:

fd = open(filename, O_RDWR | O_CREAT, mode); /* but not O_TRUNC */

to get the actual file created if needed, followed by an fdopen()
call with either "r+" or "w+" to get the C-style "FILE *" stream.
Why an appropriate mode name was not put into C99 is something of
a mystery to me, though.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
41363
by: Paul Telco | last post by:
Hello, I'm a new user designing a simple database to retrieve pre-prepared docunents for printing. I have five tables, a form to design the documents, a form to customise and retrieve the documents, a query to pull the data together from the tables and a report which formats the document with the custom data ready to print. It works very well unless:
30
35880
by: S. van Beek | last post by:
Dear reader A record set can be empty because the condition in the query delivers no records. Is there a VBA code to check the status of a record set, record set empty
1
5583
by: Oleg Ogurok | last post by:
Hi all, I want to use RegularExpressionValidator to enforce non-empty integer format in a TextBox. However, the validator doesn't give the error when the textbox is empty. For example, if ValidationExpression is \d+ or even \d{1,}, the validator still allows empty field. Must I use an additional RequiredFieldValidator? -Oleg.
3
30203
by: puja | last post by:
hi all, In asp.net 2.0 there is a limit on file size upload of 4MB. I know this limit can be increased in web.config file. Is there any way to check the file size before upload ? if user is trying to upload file size more than 4MB then just display a message that file size is too big and can't be uploaded. thanks
7
53921
by: lphang | last post by:
I am reading a simple text file that will contains three set of string values as follow: "1234567", "ABC123456", "" I have my codes as follow trying to check for an empty string, with the input string as above, I can never get it to display "testid is empty", Any idea why the test failed?: FileData = open(filename, "r") Filecontents = FileData.readline().strip() FileData.close()
1
4277
by: jtertin | last post by:
I am currently using the following code to make sure a file is writable (i.e. is not in use) by using the CanWrite method of the FileStream object. Using the code below, the TextWriter is still trying to write to the file and is throwing an exception (File... in use by another process) whenever the output file (strFileName) is open. I am trying to prevent it from writing to it at all if this is the case... Any insight? Public...
2
9843
Manikgisl
by: Manikgisl | last post by:
HI. How to check File exists in Web Share C# try { WebRequest request = HttpWebRequest.Create("http://www.microsoft.com/NonExistantFile.aspx"); request.Method = "HEAD"; // Just get the document headers, not the data. request.Credentials = System.Net.CredentialCache.DefaultCredentials; // This may throw a WebException:
3
8268
Frinavale
by: Frinavale | last post by:
Hi there! I'm hoping that someone knows how to check the size of a file before it is uploaded to the server using JavaScript. I have seen suggested solutions using an ActiveX control to check the file size; however, I'm not happy with this solution because my application is designed to work in multiple browsers and ActiveX is limited to Internet Explorer. I cannot check the file size on the web server because IIS throws the following...
3
2965
by: akshalika | last post by:
I want regular expression which check for empty. pls help me.
10
21080
by: klharding | last post by:
I am reading the contents of a text file into variables. All works well if the text file does not exist, or it does exist and contains 4 rows of data. But I need to account for rows being empty or null. How can I check this? string filename = @"C:\Program Files\Picture Capture\Settings.txt"; if (File.Exists(filename)) { StreamReader reader = new StreamReader(filename); string strAllFile =...
0
8996
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8832
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9566
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9388
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9254
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8256
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6800
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4608
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4879
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.