Com 212 intro to system programming book Theory


ch1a.c tries to open the file huangj/nonexist



Download 0.65 Mb.
View original pdf
Page50/72
Date13.05.2021
Size0.65 Mb.
#56617
1   ...   46   47   48   49   50   51   52   53   ...   72
com-212-introduction-to-system-programming-theory
9833 SS1 FISHERY LESSON NOTE
ch1a.c tries to open the file
huangj/nonexist
for reading. That file doesn't exist. Thus, fopen returns NULL (read the man page for fopen), and sets errno to flag the error. When you run the program, you'll see that errno was set to 2. To see what that means, you can do one of two things

1. Lookup the errno value in /usr/include/errno.h ( You will have to eventually look at
/usr/include/sys/errono.h on UNIX flavor machines since on that type of system, the C standard errno.h does have "#include < sys/errno.h >" in it. You'll seethe line

define ENOENT 2 /* No such file or directory */

2. Use the procedure "perror()" -- again, read the man page. It prints out what the errno means. Thus, the output off is

f = null. errno = 2

f No such file or directory This is the standard interface for errors.
ASSERT
Most of the time, there is a need to make assumptions when you write code. Everybody does it. But what if the assumption is wrong Is there a good way to check it The answer is to use
assert. The most typical use of the assert (very likely implemented as a macro on most operating systems you can find) is to identify program errors during development. The argument given to

Page | 51
assert should be chosen so that it holds true only if the program is operating as intended. The macro evaluates the assert argument and, if the argument expression is false (0), alerts the user and halts program execution. No action is taken if the argument is true (nonzero. When an assertion fails, an output message with the following text is generated assertion failed in file name inline num where name is the name of the source file and num is the line number of the assertion that failed. The liberal use of assertions throughout your programs can catch errors during development. A good rule of thumb is that you should write assertions for any assumptions you make. For example, if you assume that an argument is not NULL, use an assertion statement to check for that condition. void checkerror_strcpy(char * src, char *dst)
{ assert(src!=dst); assert(src!=NULL); assert(dst!=NULL);
} Here we check that some assumptions we made for strcpy are true. After we are sure there are no errors in the software, we can easily disable all assertion checks adding "#define NDEBUG" before where "#include < assert.h >" appears in the source code.

Download 0.65 Mb.

Share with your friends:
1   ...   46   47   48   49   50   51   52   53   ...   72




The database is protected by copyright ©ininet.org 2024
send message

    Main page