Olivier wrote On 07/10/06 15:05,:
Dear all,
I thought the code
-----------------------------
pt_fichier_probleme = fopen(nom_fichier, "w");
if(pt_fichier_probleme == NULL){
message_warning_s
("Erreur l'ouverture du fichier\n%s\n", (gchar *)nom_fichier);
return;}
else {
rewind(pt_fichier_probleme); /* Be sure we're at beginning */
if(feof(pt_fichier_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_fichier_probleme);
return;};
};};
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>