473,837 Members | 1,477 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to detect an empty file?

Dear all,

I thought the code
-----------------------------
pt_fichier_prob leme = fopen(nom_fichi er, "w");

if(pt_fichier_p robleme == NULL){
message_warning _s
("Erreur l'ouverture du fichier\n%s\n", (gchar *)nom_fichier);
return;}
else {
rewind(pt_fichi er_probleme); /* Be sure we're at beginning */
if(feof(pt_fich ier_probleme) == 0){
/* We are not at end of buffer ... It means the
file already has some content!! */
if( AskConfirmation (user_data) == 0){
/* L'utilisateur ne veut pas qu'on ecrive sur le fichier !!*/
fclose(pt_fichi er_probleme);
return;};
};};
-----------------------------

was an excellent way of
-- opening the file nom_fichier for writing,
-- detecting a mistake if it was not possible,
-- if the file was not empty, the askign the
user whether it still wants to overwrite it.
(that's AskConfirmation : a window with the question and so on)
As it turns out, confirmation is always asked :-(

Help?
Best !
Amities,
Olivier
Jul 10 '06 #1
32 5867

Olivier wrote:
Dear all,

I thought the code
<snip>

OT but ... just use stat(). It will tell you

a) if the file or directory exists
b) What sort of entry is it [file, directory, symlink, pipe, etc]
c) The size

Peace!

Tom

Jul 10 '06 #2
In article <11************ *********@b28g2 000cwb.googlegr oups.com>,
Tom St Denis <to********@gma il.comwrote:
>OT but ... just use stat(). It will tell you
>a) if the file or directory exists
b) What sort of entry is it [file, directory, symlink, pipe, etc]
c) The size
stat() is not part of standard C. Neither are directories, symlinks,
pipes, "etc".
--
There are some ideas so wrong that only a very intelligent person
could believe in them. -- George Orwell
Jul 10 '06 #3
Olivier wrote:
Dear all,

I thought the code
-----------------------------
pt_fichier_prob leme = fopen(nom_fichi er, "w");

Opening the file in "w" mode truncates
the file to zero length if fopen was successful,
so there's no need to check for file size afterward.

Perhaps you were thinking of opening the file
in "r+" mode?
if(pt_fichier_p robleme == NULL){
message_warning _s
("Erreur l'ouverture du fichier\n%s\n", (gchar *)nom_fichier);
return;}
else {
rewind(pt_fichi er_probleme); /* Be sure we're at beginning */
if(feof(pt_fich ier_probleme) == 0){
/* We are not at end of buffer ... It means the
file already has some content!! */
if( AskConfirmation (user_data) == 0){
/* L'utilisateur ne veut pas qu'on ecrive sur le fichier !!*/
fclose(pt_fichi er_probleme);
return;};
};};
-----------------------------

was an excellent way of
-- opening the file nom_fichier for writing,
-- detecting a mistake if it was not possible,
-- if the file was not empty, the askign the
user whether it still wants to overwrite it.
(that's AskConfirmation : a window with the question and so on)
As it turns out, confirmation is always asked :-(
Determine the difference in file position between
the start and end of the file with 'fseek' and 'ftell'.

--
Hope this helps,
Steven

Jul 10 '06 #4

Walter Roberson wrote:
In article <11************ *********@b28g2 000cwb.googlegr oups.com>,
Tom St Denis <to********@gma il.comwrote:
OT but ... just use stat(). It will tell you
a) if the file or directory exists
b) What sort of entry is it [file, directory, symlink, pipe, etc]
c) The size

stat() is not part of standard C. Neither are directories, symlinks,
pipes, "etc".
I recognized that by saying "OT" so pointing this out is redundant. No
reason I can't give the dude a three second tip. Tell the dude it's OT
and then point them in the right direction. In theory, you've not only
helped them but helped clear up the group.

Just replying to someone that has already acknowledged that it's OT
with a comment about it being OT is pathetic and lame.

Tom

Jul 10 '06 #5
In article <44************ **********@news .free.fr>,
Olivier <Ol**@nowhere.w dwrote:
>pt_fichier_pro bleme = fopen(nom_fichi er, "w");
>if(pt_fichier_ probleme == NULL){
message_warning _s
("Erreur l'ouverture du fichier\n%s\n", (gchar *)nom_fichier);
return;}
else {
rewind(pt_fichi er_probleme); /* Be sure we're at beginning */
if(feof(pt_fich ier_probleme) == 0){
/* We are not at end of buffer ... It means the
file already has some content!! */
Two mistakes:

1) Using "w" tells fopen() to truncate the file to zero length if it
exists. Use "r+" (or "r+b") instead.

2) feof() is not set until at least one character of I/O is attempted.
You could -try- to fseek() to the end of the file. If you do that on
a text stream, the result will be a [theoretically] opaque position,
but on a binary stream ("r+b") the fseek() result can be read off
directly in characters and so can be meaningfully compared to 0.

Note: If you need to open in binary to do the fseek() test then you
can always freopen() later without the "b" flag if you really want
to work with text instead of binary.
--
All is vanity. -- Ecclesiastes
Jul 10 '06 #6
In article <11************ **********@s13g 2000cwa.googleg roups.com>,
Tom St Denis <to********@gma il.comwrote:
>
Walter Roberson wrote:
>In article <11************ *********@b28g2 000cwb.googlegr oups.com>,
Tom St Denis <to********@gma il.comwrote:
>OT but ... just use stat(). It will tell you
>stat() is not part of standard C. Neither are directories, symlinks,
pipes, "etc".
>I recognized that by saying "OT" so pointing this out is redundant. No
reason I can't give the dude a three second tip. Tell the dude it's OT
and then point them in the right direction. In theory, you've not only
helped them but helped clear up the group.
Except you haven't helped the OP, because stat() does not exist in
all systems. The code the OP gave had no clue as to which operating system
was in use. For example in a number of versions of MS Windows, the
closest equivilent would be one of the _stat*() calls.

Your proposed solution also would require that the user open
the file-descriptor can of worms: you could have at least said fstat()
to be closer to the normal C I/O library.
When you give OT answers, you should at the very least qualify them
by naming the solution domain (e.g., "Linux 3.2", "Windows NT and
later").
--
"It is important to remember that when it comes to law, computers
never make copies, only human beings make copies. Computers are given
commands, not permission. Only people can be given permission."
-- Brad Templeton
Jul 10 '06 #7


Olivier wrote On 07/10/06 15:05,:
Dear all,

I thought the code
-----------------------------
pt_fichier_prob leme = fopen(nom_fichi er, "w");

if(pt_fichier_p robleme == NULL){
message_warning _s
("Erreur l'ouverture du fichier\n%s\n", (gchar *)nom_fichier);
return;}
else {
rewind(pt_fichi er_probleme); /* Be sure we're at beginning */
if(feof(pt_fich ier_probleme) == 0){
/* We are not at end of buffer ... It means the
file already has some content!! */
if( AskConfirmation (user_data) == 0){
/* L'utilisateur ne veut pas qu'on ecrive sur le fichier !!*/
fclose(pt_fichi er_probleme);
return;};
};};
-----------------------------

was an excellent way of
-- opening the file nom_fichier for writing,
Yes, it does that.
-- detecting a mistake if it was not possible,
It does that, too.
-- if the file was not empty, the askign the
user whether it still wants to overwrite it.
Too late. If the file does not exist, fopen(...,"w")
creates a new, empty file. If the file exists already,
fopen(...,"w") makes it empty. Either way, the file is
empty after fopen() succeeds, and any data it might have
contained is gone.
(that's AskConfirmation : a window with the question and so on)
As it turns out, confirmation is always asked :-(
That is because feof() does not mean what you think
it does. feof() does not ask the question "Is the stream
positioned at the end of the file?" Rather, feof() asks
"Has the end of the file been reached?" Although these
seem similar (and are related), they are not quite the
same. A stream "reaches the end" of a file not by arriving
at the e-o-f position, but by trying (and failing) to go
past that position. In other words, feof() does not predict
whether the next I/O operation would occur at e-o-f, but
instead tells why an I/O operation failed: was it because
the operation tried to go past e-o-f, or was it for some
other reason (like a disk failure)?

If your fopen() succeeds, the stream is positioned at
the beginning of the empty file (which is also the end).
The rewind() presumably "succeeds" because it has nothing
to do: the stream is already at the start of the file.
You then ask feof() whether a previous I/O operation failed
by running off the end of the file; there has been no such
failure, so feof() says "No."

C has no perfect solution to your problem. One possibility
is to use fopen(...,"r") first, just to test whether the file
exists. If this fopen() succeeds, fclose() it and ask the
user for instructions; do fopen(...,"w") only if the user
chooses to overwrite the file. This is not bullet-proof for
a number of reasons: The first attempt might fail for some
reason other than "no such file," some other program might
create the file two microseconds after your program decides
that it doesn't exist, and so on. Still, it's about the best
you can do without resorting to system-specific code.

<off-topic>

A technique that works on POSIX systems is to open() the
file using the O_EXCL flag and then use fdopen() to attach a
C I/O stream to the resulting file descriptor.

</off-topic>

--
Er*********@sun .com

Jul 10 '06 #8
[...]
C has no perfect solution to your problem. One possibility
is to use fopen(...,"r") first, just to test whether the file
exists. If this fopen() succeeds, fclose() it and ask the
user for instructions; do fopen(...,"w") only if the user
chooses to overwrite the file.
Thanks to all of you. That's the solution I've finally chosen
after having had a nice but aborted trip towards <sys/stat.h>
I just couldn't make that work. That's most probably for when
I'll be older :-p

Best !
Amities,
Olivier
Jul 10 '06 #9

Walter Roberson wrote:
In article <11************ **********@s13g 2000cwa.googleg roups.com>,
Tom St Denis <to********@gma il.comwrote:

Walter Roberson wrote:
In article <11************ *********@b28g2 000cwb.googlegr oups.com>,
Tom St Denis <to********@gma il.comwrote:
OT but ... just use stat(). It will tell you
stat() is not part of standard C. Neither are directories, symlinks,
pipes, "etc".
I recognized that by saying "OT" so pointing this out is redundant. No
reason I can't give the dude a three second tip. Tell the dude it's OT
and then point them in the right direction. In theory, you've not only
helped them but helped clear up the group.

Except you haven't helped the OP, because stat() does not exist in
all systems. The code the OP gave had no clue as to which operating system
was in use. For example in a number of versions of MS Windows, the
closest equivilent would be one of the _stat*() calls.
Tom's reply was more helpful than saying nothing. The OP can
certainly google for stat and fstat and at the very least discover
that they are unrelated to the platform of interest. In doing so,
the OP may discover that the platform of interest does contain
a stat()-like call of which he was formerly unaware. It is
entirely likely that the OP simply is not aware that functionality
such as stat is available, so Tom's answer is completely
appropriate.
When you give OT answers, you should at the very least qualify them
by naming the solution domain (e.g., "Linux 3.2", "Windows NT and
later").
Just out of curiousity, what is Linux 3.2? kernel.org shows 2.6.17.4
as
the most recent stable release...surel y you're not suggesting that
the OP use a radically unstable and indeed unheard of kernel?

Jul 10 '06 #10

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

Similar topics

13
2340
by: vega | last post by:
How do I detect empty tags if I have the DOM document? For example: <br /> and <br></br> I tried org.w3c.dom.Node.getFirstChild(), it returns null for both <br /> and <br></br> I also tried getNodeValue(), they both returns null also. I know <br /> and <br></br> are the same from the xml spec. Is there any way to tell the different syntax using DOM parser?
23
15618
by: Michel Bany | last post by:
I am trying to parse responseXML from an HTTP request. var doc = request.responseXML; var elements = doc.getElementsByTagName("*"); the last statement returns an empty collection when running from IE6. It returns the expected collection when running under Firefox or Mozilla. Anybody can explain ? Michel.
5
1499
by: John Smith | last post by:
How can I detect a NULL string using C# ? Thanks.
1
5415
by: Roy | last post by:
Hi, I have a problem that I have been working with for a while. I need to be able from server side (asp.net) to detect that the file i'm streaming down to the client is saved completely/succsessfully on the client's computer before updating some metadata on the server (file downloaded date for instance) However, All examples i have tried, and all examples I have found that other people says works - doesn't work for me :-(
4
4063
by: Dst | last post by:
This is what i'm trying to do: I'm porting a windows app to a web app. I have a webform which will edit some data stored in a database. The data needs to be locked in the database, while editing. On first page load: Create a custom rowlock object and store it in viewstate. When user clicks on edit, retrieve the viewstate object and lock the row in the database.
2
7088
by: MagicMyth | last post by:
Hi all, I’m creating a site that allows file uploads to registered users. I’ve got a system in place where if the user uploads a overly large file that it would automatically warn them off the offence and keep a record of it, if it was way over the file size limit I allow for (naturally the file is destroyed as well). If they continued to try to upload large files they would receive a temp ban. This relies on the system being able to determine...
6
1762
by: lasing | last post by:
Hi all, recently encounter following bugs: if (a b); //<- bug in the careless ";" here return 0; Due to the extra ";" in the if statement line, it always return 0. Anyone know g++ has any compiler - warning flag to detect this kind of
4
3628
by: ShadowLocke | last post by:
Hi, Im not very experienced with XSL, this is my first run in with it. I found an XSL file that converts a dataset to an excel readable format. The problem I have is when the dataset has a null value for a column, it does not add an empty element for the column. Is there any way I can detect this? Excel.xsl: <xsl:stylesheet version="1.0" xmlns="urn:schemas-microsoft-com:office:spreadsheet"
2
2454
by: Lambda | last post by:
I'd like to load a lot of data into a hashtable, when the memory is used up, I'll write the data to a file. I'm trying to use std::tr1::unordered_map to implement that. My question is if I insert too many data into the map, what will happen? Does unordered_map need continuous memory like vector? How to detect that there is no free memory available? Can I limit the amount of memory that is used by a container? And last, is it the right...
0
9839
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
9682
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
10871
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
10268
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...
1
7806
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
5668
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...
1
4474
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4039
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3123
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.