If fopen fails, is there a way to know why? 28 33186
Sathyaish <Vi************ ****@yahoo.com> spoke thus: If fopen fails, is there a way to know why?
If by "fails" you mean "returns NULL", yes. The global variable errno
(found in <errno.h>) contains information about what went wrong; you
can use perror() to print that information as a readable string.
--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cybers pace.org | don't, I need to know. Flames welcome.
In article <cj**********@c hessie.cirr.com >,
Christopher Benson-Manica <at***@nospam.c yberspace.org> wrote: Sathyaish <Vi************ ****@yahoo.com> spoke thus:
If fopen fails, is there a way to know why? If by "fails" you mean "returns NULL", yes. The global variable errno (found in <errno.h>) contains information about what went wrong; you can use perror() to print that information as a readable string.
If I'm not mistaken, fopen isn't required to set errno if it fails.
(Though most implementations that attempt to provide nonzero QoI do
arrange for it to be set usefully.)
dave
--
Dave Vandervies dj******@csclub .uwaterloo.caClaiming that ANSI C does not allow a weird author at the keyboard is wrong.
Thanks for the clarification. For a moment there I was afraid I'd have to find
other work. --Ben Pfaff and Michael M Rubenstein in comp.lang.c Vi************* ***@yahoo.com (Sathyaish) writes: If fopen fails, is there a way to know why?
You can examine errno or look at the corresponding message
returned by strerror(). It's not guaranteed to work portably,
but reasonable implementations will provide a useful message.
--
A competent C programmer knows how to write C programs correctly,
a C expert knows enough to argue with Dan Pop, and a C expert
expert knows not to bother.
>If fopen fails, is there a way to know why?
errno might (*MIGHT*) tell you why. Or it might not. fopen() is
not guaranteed to set errno, but in my opinion it is worth presenting
the information to the user anyway. You can turn the errno code into
a supposedly-human-readable message with strerror() or perror().
#include <stdio.h>
#include <stdlib.h>
FILE *f;
f = fopen(name, "r");
if (f == NULL) {
perror(name);
exit(EXIT_FAILU RE);
}
This code might give you a message like:
foo.txt: Permission denied
or
foo.txt: too many open files
or it might give you a message like:
foo.txt: Not a typewriter
or
foo.txt: Error 0
In creating error messages, it's a good idea to include WHAT failed,
on WHAT object, and WHY. The above examples don't say "opening for
read", and they really should, especially if the program may do
other things, like opening files for write or deleting them. If
the object is a file, include it's name (assuming it's available -
the name of stdout or stdin probably isn't). perror() or strerror()
will give you some idea of the WHY, sometimes.
Gordon L. Burditt
Christopher Benson-Manica wrote: Sathyaish <Vi************ ****@yahoo.com> spoke thus:
If fopen fails, is there a way to know why?
If by "fails" you mean "returns NULL", yes. The global variable errno (found in <errno.h>) contains information about what went wrong; you can use perror() to print that information as a readable string.
FYI, this is true of many C implementations but it
is *not* required by the Standard. Some people think
that's a reason not to use perror() after fopen() fails:
the error message may have nothing at all to do with the
failure and could be misleading. Others (myself among
them) take the optimistic view that the error message
might be helpful, and are accustomed to treating all such
messages with just a little suspicion. Some go so far
as to decorate the message with a disclaimer:
FILE *fptr = fopen(filename, mode);
if (fptr == NULL) {
fprintf (stderr, "Failed to open %s\n"
"The reason *may* have been %s\n",
filename, strerror(errno) );
...
}
Take your pick.
-- Er*********@sun .com
Eric Sosman <er*********@su n.com> wrote: FYI, this is true of many C implementations but it is *not* required by the Standard. Some people think
[snip]
fread/fwrite are not required.
Same for fgetc/fputc/fgets/etc...
fsetpos/fgetpos are.
ftell is, but fseek is not.
Functions like fgetwc are required to set errno only
with specific value, but not otherwise. fgetws is not
required to set errno.
These are just a couple of examples. I wonder why we have to have
such a mess. Why couldn't the Standard require all functions that
interface with the system to always set errno, or to set it to
some EUNKNOWN value if error information is unavailable?
In some cases it's obvious the error information is available
and the function could set errno (eg. if ftell can set errno, I don't
see a reason why fseek couldn't; same for fgetwc/fgetws pair).
I tend to avoid perror() at all, if I don't really-really have to.
--
Stan Tobias
sed 's/[A-Z]//g' to email
Eric Sosman <er*********@su n.com> spoke thus: FYI, this is true of many C implementations but it is *not* required by the Standard.
Whoops... thanks for the heads up.
--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cybers pace.org | don't, I need to know. Flames welcome.
In <cj**********@c hessie.cirr.com > Christopher Benson-Manica <at***@nospam.c yberspace.org> writes: Sathyaish <Vi************ ****@yahoo.com> spoke thus:
If fopen fails, is there a way to know why?
If by "fails" you mean "returns NULL", yes. The global variable errno (found in <errno.h>) contains information about what went wrong; you can use perror() to print that information as a readable string.
Yes, but you must be careful about it. The correct scenario is:
reset errno, call fopen, if it fails and errno is non-null you can assume
that its value provide a clue about the failure of fopen and translate it
into a meaningful message (perror or strerror), otherwise you must report
a failure for an unknown reason.
In the case of fopen, errno is the only mechanism provided by the C
language to help the programmer to generate meaningful error messages that
could help the user to understand and correct the problem. It is a shame
that the C standard doesn't require it to work.
Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
In article <ck**********@s unnews.cern.ch> , Dan Pop <Da*****@cern.c h> wrote: if it fails and errno is non-null
Shouldn't that be "nonzero"? ('Ts an integer value and not a pointer,
after all...)
dave
--
Dave Vandervies dj******@csclub .uwaterloo.ca
And don't worry about being shown up as less than perfect. We've recently
found out that Dan Pop may not be perfect. We're still working on Lawrence
Kirby. --Joe Wright in comp.lang.c This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: comp.lang.php |
last post by:
Using Linux/PHP 4.3.2 CLI:
$fileID = fopen('myfile.txt', 'r'); // WORKS JUST FINE
Using Linux/PHP 4.3.8 CLI:
$fileID = fopen('myfile.txt'); // THROWS WARNING 'no such file or
directory "myfile.txt"
Using Windows XP/PHP 5.0.4 CLI:
|
by: Tank |
last post by:
ld.so.1: internal: malloc failed
I'm getting the above on a simple fopen() in a production program. I
know that fopen calls malloc, but what would cause this and how do I
fix it? Have I hit some kind of # files open limit or something?
I'm running in Solaris 2.6.
Barry
Perot Systems
|
by: Patrice |
last post by:
Hi,
I would to call fopen function several time in my application.
This application permits to read files which path is registered in a
configuration file.
For exemple:
File 1 = toto.txt
File 2 = tot2.txt
....File N = TotoN.txt
Then, I read each file (one by one), get adress of the beginning of
data and size of data.
|
by: Richard Hsu |
last post by:
// code
#include "stdio.h"
int status(FILE * f) {
printf("ftell:%d, feof:%s\n", ftell(f), feof(f) != 0 ? "true" :
"false");
}
int case1() {
FILE * f = fopen("c:\\blah", "wb+");
int i = 5;
|
by: Cuthbert |
last post by:
After compiling the source code with gcc v.4.1.1, I got a warning
message:
"/tmp/ccixzSIL.o: In function 'main';ex.c: (.text+0x9a): warning: the
'gets' function is dangerous and should not be used."
Could anybody tell me why gets() function is dangerous??
Thank you very much.
Cuthbert
| |
by: Julia |
last post by:
Hi, there,
I am trying to append a binary file by using:
FILE *strean;
stream = fopen( "c:\temp.dat", "ba+" ));
Is there a way that I can check if the file exists or not before
fopen, because I will call different work flow by check the status of
|
by: subramanian100in |
last post by:
Consider the following program:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv)
{
if (argc != 2)
{
printf("Usage: <program-name<text-file>\n");
|
by: Hans Fredrik Nordhaug |
last post by:
I'm trying to write to a file in the current directory - no remote
files. The subject says it all - I can add that both the directory
and the file is wordwritable. This happens on a (quite good) free
hoster in Norway which doesn't use safe mode, running PHP 5.1.6 as the
PHP info below shows ...
Test it at:
http://home.no.net/moldevbk/fopen-test/?mode=w (write - fails)
http://home.no.net/moldevbk/fopen-test/?mode=a (append - ok)...
|
by: Jim |
last post by:
Hi There,
I'm trying to read a file character by character. When I write the
file out, there is one extra character which shows on the screen as a
solid circle with a small question mark in the middle.
Here is what I have:
infile = fopen("encrypted.txt", "r");
outfile = fopen("plain.txt", "w");
|
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,...
|
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...
| |
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...
|
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...
|
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...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
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...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |