InputOutput and the Operating System - PowerPoint PPT Presentation

1 / 94
About This Presentation
Title:

InputOutput and the Operating System

Description:

Executing Commands from within a C Program. Using Pipes from within a C Program ... go go 1 2 3. 22. The Functions fopen() and fclose ... – PowerPoint PPT presentation

Number of Views:122
Avg rating:3.0/5.0
Slides: 95
Provided by: drju
Category:

less

Transcript and Presenter's Notes

Title: InputOutput and the Operating System


1
Input/Output and the Operating System
2
Outline
  • The Output Function printf()
  • The Input Function scanf()
  • The Functions fprintf(), fscanf(), sprintf(), and
    sscanf()
  • The Functions fopen() and fclose()
  • Example
  • Using Temporary Files and Graceful Functions
  • Accessing a File Randomly

3
Outline (continued)
  • File Descriptor Input/Output
  • File Access Permissions
  • Executing Commands from within a C Program
  • Using Pipes from within a C Program
  • Environment Variables
  • The C Compilers

4
Outline (continued)
  • Using the Profiler
  • Libraries
  • How to Time C Code
  • The Use of make
  • The Use of touch
  • Other Useful Tools

5
The Output Function printf()
  • In this chapter, we explain how to use some of
    the input/output functions in the standard
    library, including the details about printf() and
    scanf() we have used before.
  • We will discuss about how to save data to a file,
    or how to read data from file, by opening and
    closing file using file pointers.
  • Learn about some utilities in operating system,
    which can be very useful in developing C software.

6
The Output Function printf()
  • printf() has two nice properties
  • print a list of arguments of any length
  • printing format can be controlled by simple
    conversion specifications or formats
  • The printf() delivers its character stream to the
    standard out file stdout, which normally
    connected to the screen.

7
The Output Function printf()
  • Example

printf( "she sells d d for f" , 99, "see
shells", 3.77)
control string
list of arguments
is used to introduce a conversion character
8
The Output Function printf()
  • conversion characters in printf()

c character d, i decimal integer u unsigned
decimal character o unsigned octal integer x,
X unsigned hexadecimal integer e, E floating
point number 7.123e03 f floating-pointer g
e-form and f-form floating point number G E-form
and f-form floating point number s string
9
The Output Function printf()
  • conversion characters in printf() (cont.)

p pointer to void, hexadecimal number n pointer
to integer format printf(control string,
argument list) Examples using flag and decimal
format are shown on Page 498
10
include ltstdio.hgt int main(void) char c
'A' char s "Blue moon!"
printf("c\n2c\n-3c\ns\n3s\n.6s\n
-11.8s\n", c, c, c, s, s, s, s)
return 0
printfA.c
A A A Blue moon! Blue moon! Blue
m Blue moo
11
include ltstdio.hgt int main(void) int
i 123 double x 0.123456789
printf("d\n05d\n7o\n-9x\n-9x\n10
.5f\n-12.5e\n", i, i, i, i, i, x, x)
return 0
printfB.c
123 00123 173 7b 0x7b
0.12346 1.23457e-01
12
The Input Function scanf()
  • scanf() has two nice properties just like
    printf().
  • It also has control string and list of argument

scanf( "cccdslf" , a, b, c, n, s, x )
control string
list of argument of addresses
13
The Input Function scanf()
  • conversion characters in scanf()

c character d, i signed decimal integer u
signed decimal integer o signed octal integer x,
X hexadecimal integer e, E, f, g,
G floating-pointer number s string (no-white
space) p pointer unsigned hexadecimal integer
scanf(controlString, addresses of arguments list)
14
The Functions fprintf(), fscanf(), sprintf(), and
sscanf()
  • fprintf(), and fscanf() are file versions of
    printf() and scanf()

15
The Functions fprintf(), fscanf(), sprintf(), and
sscanf()
  • FILE is defined in stdio.h as a particular
    structure, with members that describe the current
    state of a file.
  • Three file pointers defined in stdio.h
  • stdin standard input file
  • stout standard output file
  • stderr standard error file

16
The Functions fprintf(), fscanf(), sprintf(), and
sscanf()
  • fprintf() and fscanf() function prototypes are

int fprintf(FILE fp, const char format, ) int
fscanf(FILE fp, const char format, )
17
The Functions fprintf(), fscanf(), sprintf(), and
sscanf()
write to a file pointed by fiel_ptr
the same as in printf()
fprintf(file_ptr, controlString,
other_argumentList) fprintf(stout, ) is
equivalent to printf()
18
The Functions fprintf(), fscanf(), sprintf(), and
sscanf()
read from a file pointed by fiel_ptr
the same as in scanf()
fscanf(file_ptr, controlString,
other_argumentList) fscanf(stout, ) is
equivalent to scanf()
19
The Functions fprintf(), fscanf(), sprintf(), and
sscanf()
  • sscanf() and sscanf() are string version of
    printf() and scanf()
  • write to the first argument
  • read from the first argument
  • function prototypes are

int sprintf(char s, const char format, ) int
sscanf(char s, const char format, )
20
The Functions fprintf(), fscanf(), sprintf(), and
sscanf()
sprintf(char s, controlString,
other_argumentList)
write data to the first argument
sscanf(char s, controlString, other_argumentList)

read data from the first argument
21
The Functions fprintf(), fscanf(), sprintf(), and
sscanf()
jni_at_volcano 126 more sscanf.c includeltstdio.hgt
int main() char str1"1 2 3 go", str2100,
tmp100 int a, b, c sscanf(str1, "ddds",
a, b, c, tmp) sprintf(str2, "s s d d d
\n", tmp, tmp, a, b, c) printf("s",
str2) return 0
go go 1 2 3
22
The Functions fopen() and fclose()
  • Open an input or output file, to which a file
    pointer directs.

includeltstdio.hgt int main(void) FILE ifp,
ofp ifpfopen("myfile", "r") ofpfopen("outfile
","w")
return a number
file model
fclose(ifp) fclose(ofp)
23
The Functions fopen() and fclose()
  • Open an input or output file, to which a file
    pointer directs.

check the returned number of successful conversion
while (fscanf(ifp, "d", a)1)
suma fprintf(ofp, The sum is d.\n", sum)
After we used the file, we can close the file by
calling fclose(ifp)
24
The Functions fopen() and fclose()
  • Input or output modes mode and meaning are
    listed hereby

"r" open text file for reading "w" open text
file for writing "a" open text file for
appending "rb" open binary file for
reading "wb" open binary file for
writing "ab" open binary file for appending
"r" open text file for reading and
writing "w" open text file for writing and
reading
25
The Functions fopen() and fclose()
  • If open a file, with the file mode "r", that can
    not be read, or does not exit, fopen() return a
    NULL pointer
  • If open a file, with the file mode "w", that does
    not exit, system create a one, other wise the
    file will be overwritten.
  • Between a read and a write, or write and a read,
    we invoke fflush() to flush the buffer.

26
The Functions fopen() and fclose()
  • Flush buffer
  • fflush() to flush the buffer
  • Skipping Line
  • fseek()
  • Reset position and rewind
  • fsetpos() and rewind()
  • Example

27
Example Double Spacing a File
  • Read a file, and then write to another file with
    double space
  • Use command line

28
include ltstdio.hgt include ltstdlib.hgt void
double_space(FILE , FILE ) void
prn_info(char ) int main(int argc, char
argv) FILE ifp, ofp if (argc !
3) prn_info(argv0) exit(1)
ifp fopen(argv1, "r") / open for
reading / ofp fopen(argv2, "w") /
open for writing / double_space(ifp, ofp)
command line arguments
29
fclose(ifp) fclose(ofp) return
0 void double_space(FILE ifp, FILE ofp)
int c while ((c getc(ifp)) ! EOF)
putc(c, ofp) if (c '\n')
putc('\n', ofp) / found a newline -
duplicate it /
30
void prn_info(char pgm_name) printf(
"Your command is wrong!\n")
printf("\nsss\n\nss\n\n", "Usage ",
pgm_name, " infile outfile", "The
contents of infile will be double-spaced ",
"and written to outfile.")
31
A is for apple or alphabet pie which all get a
slice of, come taste it and try.
input (existed)
command
a.out input output
output generated
A is for apple or alphabet pie which all get a
slice of, come taste it and try.
32
Using Temporary Files and Graceful Functions
  • Same algorithm, except using tmpfile() in library
    to create a temporary binary file
  • Grace version of fopen()
  • Open with file mode "wb"
  • It will allow to open one file for read and write

33
/ Replicate a file with caps. / in
dbl_space directory include ltctype.hgt include
ltstdio.hgt include ltstdlib.hgt FILE
gfopen(char filename, char mode) int
main(int argc, char argv) int c
FILE fp, tmp_fp if (argc ! 2)
fprintf(stderr, "\nsss\n\ns\n\n",
"Usage ", argv0, " filename",
34
"The file will be doubled and some letters
capitalized.") exit(1) fp
gfopen(argv1, "r") tmp_fp tmpfile()
while ((c getc(fp)) ! EOF)
putc(toupper(c), tmp_fp) rewind(tmp_fp)
fprintf(fp, "---\n") while ((c
getc(tmp_fp)) ! EOF) putc(c, fp)
return 0
35
FILE gfopen(char filename, char mode)
FILE fp if ((fp fopen(filename, mode))
NULL) fprintf(stderr, "Cannot open s
- bye!\n", filename) exit(1)
return fp
36
input
write back
read in
tmp file
37
input A is for apple or alphabet pie which all
get a slice of, come taste it and try. a.out
input After execution the input A is for apple
or alphabet pie which all get a slice of, come
taste it and try. --- A IS FOR APPLE OR ALPHABET
PIE WHICH ALL GET A SLICE OF, COME TASTE IT AND
TRY.
38
Accessing a File Randomly
  • ftell() and fseek() functions are used to access
    a file randomly
  • return the current value of the file position
    indicator
  • value represents the number of bytes from the
    beginning of the file, counting from zero.

lineNumberftell(file_prt)
39
Accessing a File Randomly
  • fseek() takes three arguments
  • Only guaranted to work properly on binary files

fseek(file_ptr, offset, place)
file pointer points to a file offset offset
bytes place 0, 1, 2 meaning the beginning of
the file, the current position, and the end of
the file, respectively
40
/ Write a file backwards. / include
ltstdio.hgt define MAXSTRING 100 int
main(void) char fnameMAXSTRING int
c FILE ifp fprintf(stderr, "\nInput
a filename ") scanf("s", fname) ifp
fopen(fname, "rb") / binary mode for
MS_DOS / fseek(ifp, 0, SEEK_END) /
move to end of the file /
41
fseek(ifp, -1, SEEK_CUR) / back up one
character / while (ftell(ifp) gt 0) c
getc(ifp) / move ahead one
character / putchar(c) fseek(ifp,
-2, SEEK_CUR) / back up two characters /
return 0
42
/ Write a file backwards. / include
ltstdio.hgt define MAXSTRING 100 int
main(void) char fnameMAXSTRING int
c FILE ifp fprintf(stderr, "\nInput
a filename ") scanf("s", fname) ifp
fopen(fname, "rb") / binary mode for
MS_DOS /
43
fseek(ifp, 0, SEEK_END) / move to end of
the file / fseek(ifp, -1, SEEK_CUR) /
back up one character / while (ftell(ifp) gt
0) c getc(ifp) / move
ahead one character / putchar(c)
fseek(ifp, -2, SEEK_CUR) / back up two
characters / / // Getting the very
first character in the file // to print may be
delicate. For some operating // systems, this
program may work better. / fseek(ifp, 0,
SEEK_SET) / move to the beginning of the
file / c getc(ifp) putchar(c)
/ print the very first character /
printf("\n\n") return 0
44
.yrt dna ti etsat emoc ,fo ecils a teg lla
hcihw eip tebahpla ro elppa rof si A
A is for apple or alphabet pie which all get a
slice of, come taste it and try.
45
File Descriptor Input/output
  • File descriptor is a non-negative integer
    associated with a file
  • Library functions associated with descriptors

File Name Associated file descriptor standard
input 0 standard output 1 standard error 2
46
/ Change the case of letters in a file.
change_case.c/ include ltctype.hgt include
ltfcntl.hgt include ltunistd.hgt / use io.h
in MS_DOS / define BUFSIZE 1024 int
main(int argc, char argv) char
mybufBUFSIZE, p int in_fd, out_fd, n
in_fd open(argv1, O_RDONLY) out_fd
open(argv2, O_WRONLY O_EXCL O_CREAT,
0600) while ((n read(in_fd, mybuf,
BUFSIZE)) gt 0)
in fcntl.h, open for reading and writing,
respectively
47
for (p mybuf p - mybuf lt n p) if
(islower(p)) p toupper(p)
else if (isupper(p)) p
tolower(p) write(out_fd, mybuf, n)
close(in_fd) close(out_fd) return 0
48
a.out input output A IS FOR APPLE OR ALPHABET
PIE which all get a slice of, come taste it and
try. a is for apple or alphabet pie WHICH ALL
GET A SLICE OF, COME TASTE IT AND TRY.
49
File Access Permissions in UNIX
Mnemonic Bit Octal r-- 100 04 -w- 010 02 --x
001 01 rw- 110 06 r-x 101 05 -wx 011 03 r
wx 111 07
50
File Access Permissions in UNIX
Example ----------
Exampledrwxr-xr-x
d
5
others
7
5
octal representation is 755
user
rwx
group
rwx
rwx
chmod 755
51
Executing Commands from Within a C Program
  • The library function system() provides access to
    operating system commands
  • You can build OP commands inside the C program
  • Example

includeltstdio.hgt int main()
system("date") return 0
Sun Feb 24 122059 CST 2002
system("date")
52
Executing Commands from Within a C Program
  • Example

/ // This program uses system() to invoke the
dir command (MS-DOS), // but changes all letters
written to the screen to lowercase. / include
ltctype.hgt include ltstdio.hgt include
ltstdlib.hgt define MAXSTRING 100

53
int main(void) char commandMAXSTRING,
tmp_filename int c FILE ifp
tmp_filename tmpnam(NULL) /
sprintf(command, "dir gt s", tmp_filename) /
sprintf(command, "ls gt s", tmp_filename)
system(command) ifp fopen(tmp_filename,
"r") while ((c getc(ifp)) ! EOF)
putchar(tolower(c)) remove(tmp_filename)
return 0
Result just like use ls in UNX
read_me a.out pgm0 pgm0.c pgm1.c pgm2.c
54
system ("ls -al gtoutput")
total 92 drwxr-xr-x 2 jni students
1024 Feb 24 1607 . drwxr-xr-x 14 jni
students 1024 Feb 24 0846 .. -rwxr-xr-x 1
jni students 139 Feb 5 1512
READ_ME -rwx------ 1 jni students
20480 Feb 24 1607 a.out -rw------- 1 jni
students 0 Feb 24 1608
output -rwx------ 1 jni students
20480 Feb 24 1600 pgm0 -rw------- 1 jni
students 96 Feb 24 1600 pgm0.c -rwxr-xr-x
1 jni students 634 Feb 24 1607
pgm1.c -rwxr-xr-x 1 jni students
545 Feb 5 1512 pgm2.c
system(a.out) run another executable C program
in the current program, very useful
55
Using Pipes from within a C Program
  • Use popen() and pclose() functions
  • the first argument to popen() is a string that is
    interpreted as a command to the operating system,
    the second is file mode
  • It creates a pipe between the calling environment
    and system command that is executed.


56
/ // This program uses popen() to invoke the ls
command (UNIX), // but changes all letters
written to the screen to uppercase. / include
ltctype.hgt include ltstdio.hgt int main(void)
int c FILE ifp ifp popen("ls",
"r") while ((c getc(ifp)) ! EOF)
putchar(toupper(c)) pclose(ifp) return
0
ls READ_ME a.out pgm1.c pgm2.c
a.out READ_ME A.OUT PGM1.C PGM2.C
57
Environment Variables
include ltstdio.hgt int main(int argc, char
argv, char env) int i for (i
0 envi ! NULL i) printf("s\n",
envi) return 0

58
Environment Variables
USERjni LOGNAMEjni HOME/space/jni PATH/usr/sbi
n/opt/softbench/bin/usr/bin /usr/ccs/bin/usr/c
ontrib/bin/usr/dt/bin/opt/ansic/bin /usr/bin/X1
1/usr/contrib/bin/X11/opt/dynatext/bin/opt/aCC/
bin /opt/CC/bin/opt/langtools/bin/opt/fortran/b
in/opt/fortran90/bin /opt/fortran90/contrib/bin
/opt/graphics/phigs/bin/opt/java/bin /opt/pascal
/bin/opt/ved/bin/opt/imake/bin /opt/graphics/co
mmon/bin/opt/wt/bin/usr/vue/bin /usr/divms/bin
.

59
MAIL/var/mail/jni SHELL/bin/tcsh TZCST6CDT SSH_
CLIENT64.6.85.116 1660 22 SSH_TTY/dev/pts/4 TERM
vt100 HOSTTYPEhp9000s700 VENDORhp OSTYPEhpux M
ACHTYPEpa_risc SHLVL1 PWD/space/jni/.public-htm
l/PC/examples/ch12/environment GROUPstudents HOST
butte MANPATH/usr/share/man/L/usr/share/man/u
sr/contrib/man/L /usr/contrib/man/opt/graphics/
common/man
60
/opt/upgrade/share/man/L/opt/upgrade/share/man
/usr/dt/share/man/opt/pd/share/man/L/opt/pd/sha
re/man /opt/hparray/share/man/L/opt/hparray/sha
re/man /opt/ignite/share/man/L/opt/ignite/share
/man /opt/aCC/share/man/L/opt/aCC/share/man/op
t/audio/share/man /opt/blinklink/share/man/opt/a
nsic/share/man/L /opt/ansic/share/man/opt/langt
ools/share/man/L /opt/langtools/share/man/opt/C
C/share/man /opt/fortran/share/man/L/opt/fortra
n/share/man /opt/fortran90/share/man/L/opt/fort
ran90/share/man /opt/fortran90/contrib/man/opt/p
erf/man/L/opt/perf/man /opt/wt/share/man/opt/i
make/man/opt/pascal/share/man /opt/softbench/sha
re/man/L/opt/softbench/share/man /opt/ved/share
/man/usr/divms/man/L/usr/divms/man UNAME/usr/b
in/uname EDITORvi
61
VISUALvi NNTPSERVERnews.uiowa.edu PRINTERp346 L
INES31 COLUMNS98 ETCCSHRCpts/4
62
In C, we can use getenv() function to obtain
capitalized environment variables
include ltstdio.hgt include ltstdlib.hgt int
main(int argc, char argv, char env)
printf("ss\nss\nss\nss\n", "
Name ", getenv("NAME"), " User
", getenv("USER"), " Shell ",
getenv("SHELL"), "Home directory ",
getenv("HOME")) return 0
63
Result
Name User jni Shell
/bin/tcsh Home directory /space/jni
64
The Popular C Compilers
  • There are many C compilers. Here lists the
    popular ones for reference


cc system supported native C compiler acc early
version of ANSI C compiler from Sun
Micro bc Borland C/C compiler, integrated
environment bcc Borland C/C compiler, command
line version gcc GNU C compiler from the Free
Software Foundation hc High C compiler from
Metaware occ Oregan C compiler from Oregon
software qc Quick C compiler from Microsoft
65
The Popular C Compilers
tc Turbo C compiler, integrated environment from
Borland tcc Turbo C compiler, command line
version from Borland
  • Example

cc c main.c file1.c file2.c cc o pgm main.c
file.o file2.o
66
The Popular C Compilers
  • Compiling Option List

-c Compile only, generate corresponding .o
files -g Generate code suitable for the
debugger -o name Put executable output code in
name -p Generate code suitable for
profile -v Verbose option, generates a lots of
information -D namedef Place at the top of each
.c file the line define name def. -E invoke
the preprocessor but not the compiler

67
The Popular C Compilers
  • Compiling Option List

-I dir Look for include files in the directory
dir -M Make a makefile -O Attempt code
optimization -S Generate assembler code in
corresponding .s files

68
Using the Profile
  • Used to generate executable profile for analysis
    timing and tuning
  • command


cc p o quicksort main.c quicksort.c
69
/ quicksort.c / include "quicksort.h" void
quicksort(int left, int right) int p,
pivot if (find_pivot(left, right, pivot)
yes) p partition(left, right, pivot)
quicksort(left, p - 1) quicksort(p,
right)
70
/ Quicksort! Pointer version with macros.
quicksort.h/ include ltstdio.hgt include
ltstdlib.hgt include lttime.hgt define N
1000000 define swap(x, y) int t t x x
y y t define order(x, y) if (x gt y)
swap(x, y) define o2(x, y) order(x,
y) define o3(x, y, z) o2(x, y) o2(x, z)
o2(y, z) typedef enum yes, no
yes_no yes_no find_pivot(int left, int
right, int pivot_ptr) int partition(int
left, int right, int pivot) void
quicksort(int , int ) void wrt(char s,
int a, int n)
71
include "quicksort.h" int main(void) int
aN, i srand(time(NULL)) for (i 0 i
lt N i) ai rand() 10000
quicksort(a, a N - 1) / // Check that
the array a has been sorted // but do not
print the array. We want to // profile the
sorting, not the printing. /
72
for (i 0 i lt N - 1 i) if (ai gt
ai 1) printf("SORTING ERROR -
bye!\n") exit(1) return
0
73
/ find_pivot.c / include "quicksort.h" yes_no
find_pivot(int left, int right, int
pivot_ptr) int a, b, c, p a
left / left
value / b (left (right - left) / 2)
/ middle value / c right
/ right value / o3(a, b,
c) / order these 3 values
/ if (a lt b) / pivot will be
higher of 2 values / pivot_ptr b
return yes
74
if (b lt c) pivot_ptr c return
yes for (p left 1 p lt right p)
if (p ! left) pivot_ptr (p lt
left) ? left p return yes
return no / all elements have the
same value /
75
include "quicksort.h" int partition(int left,
int right, int pivot) while (left lt right)
while (left lt pivot) left
while (right gt pivot) --right if
(left lt right) swap(left, right)
left --right return
left
76
make It generate quicksort. quicksort It
generates mon.out file prof quicksort Time
Seconds Cumsecs Calls msec/call Name 51.3
1.60 1.60 9999 0.16 partition
14.0 0.44 2.04
remoI 9.6 0.30 2.34 1
300.00 main 7.5 0.23 2.57 1000000
0.00 _rand 7.4 0.23 2.80
mulI
77
4.2 0.13 2.93
_mcount 4.2 0.13 3.06 19999
0.01 find_pivot 0.3 0.01 3.07 19999
0.00 quicksort 0.2 0.00 3.08
divU 0.2 0.00 3.08
_monstartup 0.1 0.00 3.08
1 2.50 _srand 0.0 0.00
3.08 1 0.00 _doprnt 0.0 0.00
3.08 1 0.00 _sprintf 0.0
0.00 3.08 1 0.00 _start 0.0
0.00 3.08 1 0.00 _write 0.0
0.00 3.08 1 0.00 creat64
0.0 0.00 3.08 1 0.00 exit
0.0 0.00 3.08 1 0.00 monitor
0.0 0.00 3.08 1 0.00 open
Note Very useful when people is study and
analyze the execution efficiency!
78
Libraries
  • Many OSs provides utility libraries
  • In UNIX, ar command can be use
  • Extension name
  • in UNIX .a file
  • in DOS .lib file
  • In UNIX, the library is located in /lib/libc.a


79
Libraries
  • Use the following command to list the functions
    in libc.a


ar t /usr/lib/libc.a gt output
80
include ltstdio.hgt include ltstdlib.hgt void
gcalloc(int n, unsigned sozeof_something) void
p if ((pcalloc(n, sizeof_something))NULL) f
printf(stderr,"\nERROR calloc() failed
bye.\n\n") exit(1) return p
81
Libraries
  • Create a library file after compiling.
  • We have some .h files, for example gcalloc.h
  • Compile the .h files first


cc c gcalloc.h
It generates gcalloc.o file
82
Libraries
  • Create a library file after compiling.
  • Say, we have some .h files, for example gcalloc.h
  • Compile the .h files first


cc c gcalloc.h ( or other files)
It generates gcalloc.o file
83
Libraries
  • Now we can generate .a file


ar ruv g_lib.a gcalloc.o
It generate gcalloc.a file
84
Libraries
  • Now we need to randomize the library in a form
    that is added the loader
  • How to use the .a libraries while linking?


ranlib gcalloc.a ar creating gcalloc.a
cc o main.c file1.c file2.c gcalloc.a
85
How to Time C Code
  • How to use some timing functions in built-in
    library
  • Timing functions are in time.h library
  • clock_t and time_t are the type-defined long
    integer. In function prototypes in time.h, we
    have


typedef long clock_t typedef long time_t
86
How to Time C Code
  • time() function
  • Example


srand(time(NULL)) seeds the random-number
generator
87
include ltstdio.hgt /time_keeper.h
/ define N 100000000 / one
hundred million / void start_time(void) dou
ble wrt_time(void)
88
include ltstdio.hgt include ltstdlib.hgt include
lttime.hgt define MAXSTRING 100 typedef
struct clock_t begin_clock, save_clock
time_t begin_time, save_time
time_keeper static time_keeper tk
/ known only to this file / void
start_time(void) tk.begin_clock
tk.save_clock clock() tk.begin_time
tk.save_time time(NULL)
/ time_keeper.c /
89
double wrt_time(void) char
s1MAXSTRING, s2MAXSTRING int
field_width, n1, n2 double
clocks_per_second (double) CLOCKS_PER_SEC,
user_time, real_time user_time
(clock() - tk.save_clock) / clocks_per_second
real_time difftime(time(NULL), tk.save_time)
tk.save_clock clock() tk.save_time
time(NULL) / print the values found, and
do it neatly /
90
n1 sprintf(s1, ".1f", user_time) n2
sprintf(s2, ".1f", real_time) field_width
(n1 gt n2) ? n1 n2 printf("s.1fs\ns.1f
s\n\n", "User time ", field_width,
user_time, " seconds", "Real time ",
field_width, real_time, " seconds") return
user_time
91
/ Compare float and double multiplication times.
/ include "time_keeper.h" int main(void)
long i float a, b 3.333, c 5.555
/ arbitrary values / double x, y 3.333,
z 5.555 printf("Number of multiplies
d\n\n", N) printf("Type float\n\n")
start_time()
92
for (i 0 i lt N i) a b c
wrt_time() printf("Type double\n\n") for
(i 0 i lt N i) x y z
wrt_time() return 0
Result
Number of multiplies 100000000 Type
float User time 10.0 seconds Real time 13.0
seconds Type double User time 11.2
seconds Real time 12.0 seconds
ar ruv u_lib.a time_keeper.o a -
time_keeper.o ar creating u_lib.a ranlib u_lib.a
93
Other Useful Tools
cd C beautifier, used to pretty print C
code dbx A source-level debugger, code must be
compiled with option g diff Prints the
lines that differ in two files gdb GNU
debugger, code must be compiled with option
g grep Searches from a pattern in one or more
files a major tool for programmers indent
A C code "pretty printer with lots of
options wc Counts lines, words, and
characters in one or more files

94
Other Useful Tools
  • C can be used in conjunction with other
    high-level tools, some of which are languages in
    their own right
  • For example
  • awk, bison, csh, flex, lex, nawk, perl, sed, yacc
  • ftp gnu packages using
  • ftp preg.ai.mit.edu

Write a Comment
User Comments (0)
About PowerShow.com