Sei sulla pagina 1di 24

m  





 
m   
 

 
There is a very close link between C and most
operating systems that run our C programs.
Almost the whole of the UNIX operating system
is written in C. This Chapter will look at how C
and UNIX interface together.
       m
ï  ½½ UNIX, or a variety of UNIX, is available on many machines.
Programs written in ÷  UNIX and C should run on any of them with
little difficulty.
ï ë    ë  ½½ many programs can share a machines processing
power.
ï    ½½ hierarchical file system with many file handling routines.
ï  !! ½½ UNIX provides a powerful command interpreter that
understands over 200 commands and can also run UNIX and user½defined
programs.
ï " ½½ where the output of one program can be made the input of another.
This can done from command line or within a C program.
ï   ½½ there over 200 utilities that let you accomplish many
routines without writing new programs. „  make, grep, diff, awk, more ....
ï ! # ½½ UNIX has about 60 system calls that are at the m„ of the
operating system or the „„ of UNIX. The calls are actually written in C. All
of them can be accessed from C programs. Basic I/0, system clock access are
examples. The function open() is an example of a system call.
ï  $ # ½½ additions to the operating system.
 % ë m  


% m 
To use system calls and library functions in a C program
we simply call the appropriate C function.

Examples of standard library functions we have met


include the higher level I/O functions ½½ fprintf(), malloc() ...

Aritmetic operators, random number generators ½½


random(), srandom(), lrand48(), drand48() „  and basic C
types to string conversion are memebers of the stdlib.h
standard library.

All math functions such as sin(), cos(), sqrt() are standard


math library (math.h) functions and others follow in a
similar fashion.

For most system calls and library functions we have to


include an appropriate header file. „  stdio.h, math.h
 % ë m  


% m 
   $ #     & !     '#  
  m $   $ # #  #      $ 
 $   !"        ! &  "#
" (  $ # ( " " #     
    ##  #  !     "
$  #!" #  ""    !"  #!" 
"! #  $ # $!  !   #!! !


## !"# )!

 $ )!    #    !  (  "!
 !  " $ # $ # (   $!  $  "#
#!" $     $!    ! # 
 $ #  &  !  "   &  
!" " ! $ # !

„ !  *+

(  & $!     !  !  & 


#! #" ( (  &   ! "# $  m
       


% m 
To use all functions in this library you must
include that file:

#include <stdlib.h>

There are three basic categories of functions:


ï Arithmetic
ï Random Numbers

ï String Conversion

The use of all the functions is relatively


straightforward.


% m 

 ë m m  
m 

There are 4 basic integer functions:

Ô int abs(int number);

Ô long int labs(long int number);

Ô div_t div(int numerator,int denominator);

Ô ldiv_t ldiv(long int numerator, long int denominator);


 
m  ë
#include <stdlib.h>
#include<stdio.h>
#include<conio.h>
/* div_t is already defined in stdlib.h*/
/*typedef struct { int quot; int rem; } div_t;*/
main()
{
int num = 8, den = 3;
div_t ans;

ans = div(num,den);

printf(´Quotient = %d\n\t Remainder = %d\n", ans.quot, ans.rem);


getch();
}


% m 

ë ë


 !  !  $   "!    ! 


 ! &  #  ! !   "! 
"##  $ # " #    !  ))  " #

„  !   #!"  $!  & $! 


, $$   $$ $!     !
 #  " #  "  „„     $!
(#   #    $     ! 
  !  !  (  #!"  
 #!! #    # $   !  
 !  !      ! $      
  ( (  #   ! ,"   !
 ! $ #        "  
! #      $$  !  # , 
$$  $ # & $$  ! 
 !"  $ $ # 

Ô   ,&

Ô &  ,   

 ,    ##& " ) !  !    $! -
 ,./01 )0  ,         !" !" $ 
 ! $        &  #

ë ë
 ë
'# 2  (,5520-
'# 2#
'# 2  3 ,

' $
 0 # &36750

' $   - "$,896 8  # &

&  #, 

 3-   # &
!,
#  $ ! 3


#,

$,$ ! #,



$ ! 3 

 ,0.4*



 ë m m 

ë ë

There are several other random number generators available
in the standard library:

double drand48(void);
double erand48(unsigned short xsubi[3]);
long lrand48(void);
long nrand48(unsigned short xsubi[3]);
long mrand48(void);
long jrand48(unsigned short xsubi[3]);
void srand48(long seed);
unsigned short *seed48(unsigned short seed[3]);
void lcong48(unsigned short param[7]);

This family of functions generates uniformly distributed


pseudo½random numbers.

 m

There are a few functions that exist to convert strings to
integer, long integer and float values. They are:

ï double atof(char *string) ½½ Convert string to floating point


value.
ï int atoi(char *string) ½½ Convert string to an integer value
ï int atol(char *string) ½½ Convert string to a long integer
value.
ï double strtod(char *string, char *endptr) ½½ Convert string
to a floating point value.
ï long strtol(char *string, char *endptr, int radix) ½½ Convert
string to a long integer using a given radix.
ï unsigned long strtoul(char *string, char *endptr, int radix)
½½ Convert string to unsigned long.

 m
 ë
main()
{
char *str1 = "100";
char *str2 = "55.444";
char *str3 = " 1234";
char *str4 = "123four";
char *str5 = "invalid123";
int i;
float f;
i = atoi(str1); /* i = 100 */
printf(´ \n%d µ, i);
f = atof(str2); /* f = 55.44 */
printf(´ \n%f µ, f);
i = atoi(str3); /* i = 1234 */
printf(´ \n%d µ, i);
i = atoi(str4); /* i = 123 */
printf(´ \n%d µ, i);
i = atoi(str5); /* i = 0 */
printf(´ \n%d µ, i);
}
SEARCHING AND SORTING

ï The stdlib.h provides 2 useful functions to perform general searching


and sorting of data on any type. In fact we have already introduced
the qsort() function.
ï The qsort standard library function is very useful function that is
designed to sort an array by a key value of any type into ascending
order, as long as the elements of the array are of fixed type.

ï qsort is prototyped (in stdlib.h):

ï void qsort(void *base, size_t num_elements, size_t element_size,


ï int (*compare)(void const *, void const *));

ï Similarly, there is a binary search function, bsearch() which is


prototyped (in stdlib.h) as:

ï void *bsearch(const void *key, const void *base, size_t nel,


ï size_t size, int (*compare)(const void *, const void *));
SEARCHING EXAMPLE
#include<stdio.h>
#include<stdlib.h>

int compare_integers (const void * a, const void * b)


{
return ( *(int*)a ½ *(int*)b );
}

/*Note that the array is already sorted!*/


int my_array[] = { 5, 10, 15, 20, 25, 30 };

int main ()
{
int * ptr_item;
int searchkey;

printf ("Enter a searchkey: ");


scanf ("%d", &searchkey);

ptr_item = (int*) bsearch (&searchkey,


my_array, 6, sizeof (int), compare_integers);

if (ptr_item != NULL)
printf ("%d is found in the array.\n",*ptr_item);
else
printf ("%d is not found in the array.\n",searchkey);
return 0;
}
ë  ë m m 
Mathematics is relatively straightforward library to
use again. You must #include <math.h> and must
remember to link in the math library at
compilation(Linux/Unix OS):

cc mathprog.c ½o mathprog ½lm

A common source of error is in forgetting to include


the <math.h> file (and yes experienced programmers
make this error also). Unfortunately the C compiler
does not help much. Consider:

double x;
x = sqrt(63.9);
ë  m 
Below we list some common math functions. Apart from the note above they should be easy to use and
we have already used some in previous examples. We give no further examples here:
double acos(double x) ½½ Compute arc cosine of x.
double asin(double x) ½½ Compute arc sine of x.
double atan(double x) ½½ Compute arc tangent of x.
double atan2(double y, double x) ½½ Compute arc tangent of y/x, using the signs of both arguments to
determine the quadrant of the return value.
double ceil(double x) ½½ Get smallest integral value that exceeds x.
double cos(double x) ½½ Compute cosine of angle in radians.
double cosh(double x) ½½ Compute the hyperbolic cosine of x.
div_t div(int number, int denom) ½½ Divide one integer by another.
double exp(double x ½½ Compute exponential of x
double fabs (double x ) ½½ Compute absolute value of x.
double floor(double x) ½½ Get largest integral value less than x.
double fmod(double x, double y) ½½ Divide x by y with integral quotient and return remainder.
double frexp(double x, int *expptr) ½½ Breaks down x into mantissa and exponent of no.
labs(long n) ½½ Find absolute value of long integer n.
double ldexp(double x, int exp) ½½ Reconstructs x out of mantissa and exponent of two.
ldiv_t ldiv(long number, long denom) ½½ Divide one long integer by another.
double log(double x) ½½ Compute log(x).
double log10 (double x ) ½½ Compute log to the base 10 of x.
double modf(double x, double *intptr) ½½ Breaks x into fractional and integer parts.
double pow (double x, double y) ½½ Compute x raised to the power y.
double sin(double x) ½½ Compute sine of angle in radians.
double sinh(double x) ½ Compute the hyperbolic sine of x.
double sqrt(double x) ½½ Compute the square root of x.
void srand(unsigned seed) ½½ Set a new seed for the random number generator (rand).
double tan(double x) ½½ Compute tangent of angle in radians.
double tanh(double x) ½½ Compute the hyperbolic tangent of x.
ë  m  
The math.h library defines many (often neglected) constants.
It is always advisable to use these definitions:
HUGE ½½ The maximum value of a single½precision floating½point
number. M_E ½½ The base of natural logarithms (e).
M_LOG2E ½½ The base½2 logarithm of e.
M_LOG10E ½ The base½10 logarithm of e.
M_LN2 ½½ The natural logarithm of 2.
M_LN10 ½½ The natural logarithm of 10.
M_PI ½½ .
M_PI_2 ½½ /2.
M_PI_4 ½½ /4. M_1_PI ½½ 1/.
M_2_PI ½½ 2/.
M_2_SQRTPI ½½ 2/.
M_SQRT2 ½½ The positive square root of 2.
M_SQRT1_2 ½½ The positive square root of 1/2.
MAXFLOAT ½½ The maximum value of a non½infinite single½ precision
floating point number.
HUGE_VAL ½½ positive infinity. There are also a number a machine
dependent values defined in #include <value.h> ½½ see man value or
list value.h for further details.
    , 
 

stdio.h is a standard I/O m„„ file so do:

#include <stdio.h>

Different I/O functions can be categorized as:

ï
" 
ï !

ï #

ï ! 
    , 






Many times it is useful to report errors in a C
program. The standard library perror() is an easy
to use and convenient function. It is used in
conjunction with errno and frequently on
encountering an error you may wish to terminate
your program early. Whilst not strictly part of
the stdio.h library we introduce the concept of
errno and the function exit() here.
    , 






", 
$ #", "" 

& ",##:!


", " #  ! #    #      ,
(   #   !   $ #   !  !  "
$   #      !   ( $ !    "
 "       #   " 


 "#! &$!##"$!
$ 
'# 2 

  m"!!  # &

 


#! (m"!,  #!!"## (


!"&   !#$ #
    , 






,
 $ # ,  ""  '#  2  

& ,  

 !" !  #  $  "!   


    &    " !    &  
   # $  "!  ! ""
  (   mm  &    ##$  !
  (    
&    ##$ 
!
 #     ! $  # 
,   
 !   "!





 ë
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
main()
{
FILE *fp;
char filename[80];
printf("Enter filename: ");
gets(filename);
if (( fp = fopen(filename, "r")) == NULL)
{
perror("You goofed!");
printf("errno = %d.\n", errno);
exit(1);
}
else
{
puts("File opened for reading.");
fclose(fp);
}
return(0);
}
    , 

ë

Potrebbero piacerti anche