binary search tree for a node: the left subtree contains nodes with keys less than the node's...
TRANSCRIPT
Binary Search Tree
For a node
The left subtree contains nodes with keys less than the nodes key
The right subtree contains nodes with keys greater than the nodes key
Both the left and right subtrees must also be binary search trees
Binary Search Treevoid insert (struct node root struct node entry)
where to insert is really algorithm dependent
A generic case only entry is to replace the left node of root
if (head-gtleft)
entry-gtleft = head-gtleft-gtleft
entry-gtright = head-gtleft-gtright
head-gtleft = entry
void delete (struct node root struct node entry)
The key is to find a node that has an entry as a child
Three Cases 1) Leaf node
2) A node with one child remove the node and replace it with its child
3) A node with two children Replace the value of entry with the largest value in the left or the smallest value in the right and delete the node with largest value in the left or the smallest value in the right
struct node search (struct node root int val)DFS
struct node tmp = NULL
if (root)
return NULL
else if (root-gtdata = val)
tmp = search(root-gtleft val)
if (tmp)
tmp = search(root-gtright val)
return tmp
int main()
struct node num[10] = hellip
struct node root = 0 NULL NULL
for (int i=0 ilt10 i++)
insert (amproot ampnum[i])
hellip
return 0
BreadthDepth-first TraversalBFS 1) A-gtB-gtC-gtD-gtE-gtF-gtG-gtH2)A queue is needed to keep the nodes while the tree is being traversed
DFS 1)A-gtB-gtD-gtC-gtE-gtF-gtH-gtG2)Usually a recursive function
A
B C
D E F G
H
root
Weeks 8-9 IO
Standard IO (stdin stdout) and Pipes Formatted IO File IO
System Calls System interface to obtain services from the OS include many subsystems
Memory Scheduler FileStorage System Inter-process Communication and Network etc
A popular subsystem File system File descriptors Low level IO File Management Examples
Programs and Standard IO
ProgramProgramStandard Input(STDIN)bullKeyboardbullOutput from another programbullA file
Standard Output(STDOUT)bullScreenbullInput to another programbullA file
Standard Error(STDERR)
stdin stdout
cmd lt inputfile
cmd gt outputfile Numbered file descriptors
0 stdin used by function scanf() 1 stdout used by function printf() 2 stderr hellip
Pipes and InputOutput Redirection
When a file descriptor is assigned to something other than a terminal it is called IO redirection
A file (the contents of the file are fed to a program as if you typed it) wc lt text_file
A pipe (the output of another program is fed as input as if you typed it) The shell can attach things other than your screen to standard output
A file (the output of a program is stored in file) ls gt lsout (gtgt for append)
A pipe (the output of a program is fed as input to another program)
Pipes
cmd1 | cmd2 | cmd3 IO Redirection
cmd1 lt inputfile gt outputfile specifies the input and output file
cmd1 | cmd2 2gtamp1 | cmd3 redirect stderr(2) to stdout and input it to cmd3
Pipes
A pipe is a holder for a stream of data A pipe can be used to hold the output of one program and feed it to
the input of another Separate 2 commands with the ldquo|rdquo character
prog1prog1 prog2prog2STDOUT STDIN
RedirectionPipe Examples
wc lt test1 ls gt lsout ls gtgt lsout ls | wc
Formatted IO Output printf Input scanf Arguments a format string followed by the arguments
printf (char fmt arg1 arg2 hellip)
scanf (char fmt arg1 arg2 hellip) Arguments for scanf have to be the memory addresses
Formatting Output goes to stdout Input comes from stdin Format String regular string + conversion specification
Start of a format specification Width precision adjustment Between lsquorsquo and the conversion character in order
i) rsquo-rsquo specifies left adjustment of the converted argument
A number the minimum field width1048698 ii) lsquorsquo separates the field width from the precision A number precision
string(max num of characters) floating(num of digits after the decimal point) integer(min num of digits)
1048698 iii) l or h long or short1048698 Example Hello World (12 characters)
printf(ldquosrdquo s) -15s 10s -1510s 1510s
Refer to Chapter 72 Formatted Output1048698 Go to web page httpwwwcpluspluscomreferenceclibrarycstdioprintf for more details
String-based inputoutput
String-based input int sscanf (char str char fmt arg1 arg2 hellip)
String-based output int sprintf (char str const char format )
Examplechar st[]=ldquo321 433rdquofloat xysscanf(strdquoffrdquoampxampy)result x=321 y=433
char newst[32]sprintf(newstrdquof frdquo y x)result newst=ldquo433321rdquo
Variable length arguments
Variable length arguments A function may be called with a varying number of arguments of varying types
include ltstdarghgt ltstdiohgt a new datatype va_list declare a variable va_list ap
Associated macro functions va_start(ap last)
Initialize ap to be the va_list after the argument last This need to be done before va_arg and va_end
va_arg(ap int) Expand ap to an expression that has typevalue that match int ap moves to the next argument in the variable list
va_end(ap) Cleanup the variable argument list when done
Variable length arguments
includeltstdiohgtincludeltstdarghgtint add(int n )int main() printf(dn add(41234)) printf(dn add(3123))
return 0
int add(int n ) int i sum tmp va_list arg va_start(arg n) for(sum = i = 0 i lt n ++i) tmp = va_arg(arg int) sum += tmp va_end(arg) return sum
Variable length argumentsvoid foo(char fmt ) va_list ap int d char c p s va_start(ap fmt) while (fmt)
switch(fmt++) case s string
s = va_arg(ap char ) printf(string sn s) break
case d int d = va_arg(ap int) printf(int dn d) break
case c char c = va_arg(ap char) printf(char cn c) break
va_end(ap)
File Accesses Files and file descriptors
FILE fp FILE fopen(char name char mode)
Name can be a long path Mode a combination of lsquorrsquo lsquowrsquo lsquoxrsquo or lsquoarsquo
File inputoutput int getc(FILE fp) int putc(int c FILE fp) These works with default stdinstdout
getchar() putchar()
include ldquostdiohrdquoint main() FILE fp=fopen(ldquotesttxtrdquordquorrdquo) int c int n=0 while((c=getc(fp))=EOF) if(c==lsquo$rsquo) n++ printf(ldquofile contains d $nrdquon) fclose(fp)
File Accesses ldquorldquo Open a file for reading The file must
exist wldquo Create an empty file for writing If a file
with the same name already exists its content is erased and the file is treated as a new empty file
aldquo Append to a file Writing operations append data at the end of the file The file is created if it does not exist
r+ldquo Open a file for update both reading and writing The file must exist
w+ldquo Create an empty file for both reading and writing If a file with the same name already exists its content is erased and the file is treated as a new empty file
a+ldquo Open a file for reading and appending
Line-oriented inputoutput
int getline(char line size_t n FILE fp) char fgets(char line size_t n FILE fp)
gets(char line size_t n) buggy never use it char fputs(char line FILE fp) Donrsquot use scanf() before fgets()
Error handling
fprintf(stderr char fmt arg1 arg2 hellip) exit(1) exit with non-zero status ferror(FILE fp) test for any error on fp feof(FILE fp) test for end-of-file perror(char s)
print the error message s to stderr for the last system or library calls
Binary Search Treevoid insert (struct node root struct node entry)
where to insert is really algorithm dependent
A generic case only entry is to replace the left node of root
if (head-gtleft)
entry-gtleft = head-gtleft-gtleft
entry-gtright = head-gtleft-gtright
head-gtleft = entry
void delete (struct node root struct node entry)
The key is to find a node that has an entry as a child
Three Cases 1) Leaf node
2) A node with one child remove the node and replace it with its child
3) A node with two children Replace the value of entry with the largest value in the left or the smallest value in the right and delete the node with largest value in the left or the smallest value in the right
struct node search (struct node root int val)DFS
struct node tmp = NULL
if (root)
return NULL
else if (root-gtdata = val)
tmp = search(root-gtleft val)
if (tmp)
tmp = search(root-gtright val)
return tmp
int main()
struct node num[10] = hellip
struct node root = 0 NULL NULL
for (int i=0 ilt10 i++)
insert (amproot ampnum[i])
hellip
return 0
BreadthDepth-first TraversalBFS 1) A-gtB-gtC-gtD-gtE-gtF-gtG-gtH2)A queue is needed to keep the nodes while the tree is being traversed
DFS 1)A-gtB-gtD-gtC-gtE-gtF-gtH-gtG2)Usually a recursive function
A
B C
D E F G
H
root
Weeks 8-9 IO
Standard IO (stdin stdout) and Pipes Formatted IO File IO
System Calls System interface to obtain services from the OS include many subsystems
Memory Scheduler FileStorage System Inter-process Communication and Network etc
A popular subsystem File system File descriptors Low level IO File Management Examples
Programs and Standard IO
ProgramProgramStandard Input(STDIN)bullKeyboardbullOutput from another programbullA file
Standard Output(STDOUT)bullScreenbullInput to another programbullA file
Standard Error(STDERR)
stdin stdout
cmd lt inputfile
cmd gt outputfile Numbered file descriptors
0 stdin used by function scanf() 1 stdout used by function printf() 2 stderr hellip
Pipes and InputOutput Redirection
When a file descriptor is assigned to something other than a terminal it is called IO redirection
A file (the contents of the file are fed to a program as if you typed it) wc lt text_file
A pipe (the output of another program is fed as input as if you typed it) The shell can attach things other than your screen to standard output
A file (the output of a program is stored in file) ls gt lsout (gtgt for append)
A pipe (the output of a program is fed as input to another program)
Pipes
cmd1 | cmd2 | cmd3 IO Redirection
cmd1 lt inputfile gt outputfile specifies the input and output file
cmd1 | cmd2 2gtamp1 | cmd3 redirect stderr(2) to stdout and input it to cmd3
Pipes
A pipe is a holder for a stream of data A pipe can be used to hold the output of one program and feed it to
the input of another Separate 2 commands with the ldquo|rdquo character
prog1prog1 prog2prog2STDOUT STDIN
RedirectionPipe Examples
wc lt test1 ls gt lsout ls gtgt lsout ls | wc
Formatted IO Output printf Input scanf Arguments a format string followed by the arguments
printf (char fmt arg1 arg2 hellip)
scanf (char fmt arg1 arg2 hellip) Arguments for scanf have to be the memory addresses
Formatting Output goes to stdout Input comes from stdin Format String regular string + conversion specification
Start of a format specification Width precision adjustment Between lsquorsquo and the conversion character in order
i) rsquo-rsquo specifies left adjustment of the converted argument
A number the minimum field width1048698 ii) lsquorsquo separates the field width from the precision A number precision
string(max num of characters) floating(num of digits after the decimal point) integer(min num of digits)
1048698 iii) l or h long or short1048698 Example Hello World (12 characters)
printf(ldquosrdquo s) -15s 10s -1510s 1510s
Refer to Chapter 72 Formatted Output1048698 Go to web page httpwwwcpluspluscomreferenceclibrarycstdioprintf for more details
String-based inputoutput
String-based input int sscanf (char str char fmt arg1 arg2 hellip)
String-based output int sprintf (char str const char format )
Examplechar st[]=ldquo321 433rdquofloat xysscanf(strdquoffrdquoampxampy)result x=321 y=433
char newst[32]sprintf(newstrdquof frdquo y x)result newst=ldquo433321rdquo
Variable length arguments
Variable length arguments A function may be called with a varying number of arguments of varying types
include ltstdarghgt ltstdiohgt a new datatype va_list declare a variable va_list ap
Associated macro functions va_start(ap last)
Initialize ap to be the va_list after the argument last This need to be done before va_arg and va_end
va_arg(ap int) Expand ap to an expression that has typevalue that match int ap moves to the next argument in the variable list
va_end(ap) Cleanup the variable argument list when done
Variable length arguments
includeltstdiohgtincludeltstdarghgtint add(int n )int main() printf(dn add(41234)) printf(dn add(3123))
return 0
int add(int n ) int i sum tmp va_list arg va_start(arg n) for(sum = i = 0 i lt n ++i) tmp = va_arg(arg int) sum += tmp va_end(arg) return sum
Variable length argumentsvoid foo(char fmt ) va_list ap int d char c p s va_start(ap fmt) while (fmt)
switch(fmt++) case s string
s = va_arg(ap char ) printf(string sn s) break
case d int d = va_arg(ap int) printf(int dn d) break
case c char c = va_arg(ap char) printf(char cn c) break
va_end(ap)
File Accesses Files and file descriptors
FILE fp FILE fopen(char name char mode)
Name can be a long path Mode a combination of lsquorrsquo lsquowrsquo lsquoxrsquo or lsquoarsquo
File inputoutput int getc(FILE fp) int putc(int c FILE fp) These works with default stdinstdout
getchar() putchar()
include ldquostdiohrdquoint main() FILE fp=fopen(ldquotesttxtrdquordquorrdquo) int c int n=0 while((c=getc(fp))=EOF) if(c==lsquo$rsquo) n++ printf(ldquofile contains d $nrdquon) fclose(fp)
File Accesses ldquorldquo Open a file for reading The file must
exist wldquo Create an empty file for writing If a file
with the same name already exists its content is erased and the file is treated as a new empty file
aldquo Append to a file Writing operations append data at the end of the file The file is created if it does not exist
r+ldquo Open a file for update both reading and writing The file must exist
w+ldquo Create an empty file for both reading and writing If a file with the same name already exists its content is erased and the file is treated as a new empty file
a+ldquo Open a file for reading and appending
Line-oriented inputoutput
int getline(char line size_t n FILE fp) char fgets(char line size_t n FILE fp)
gets(char line size_t n) buggy never use it char fputs(char line FILE fp) Donrsquot use scanf() before fgets()
Error handling
fprintf(stderr char fmt arg1 arg2 hellip) exit(1) exit with non-zero status ferror(FILE fp) test for any error on fp feof(FILE fp) test for end-of-file perror(char s)
print the error message s to stderr for the last system or library calls
BreadthDepth-first TraversalBFS 1) A-gtB-gtC-gtD-gtE-gtF-gtG-gtH2)A queue is needed to keep the nodes while the tree is being traversed
DFS 1)A-gtB-gtD-gtC-gtE-gtF-gtH-gtG2)Usually a recursive function
A
B C
D E F G
H
root
Weeks 8-9 IO
Standard IO (stdin stdout) and Pipes Formatted IO File IO
System Calls System interface to obtain services from the OS include many subsystems
Memory Scheduler FileStorage System Inter-process Communication and Network etc
A popular subsystem File system File descriptors Low level IO File Management Examples
Programs and Standard IO
ProgramProgramStandard Input(STDIN)bullKeyboardbullOutput from another programbullA file
Standard Output(STDOUT)bullScreenbullInput to another programbullA file
Standard Error(STDERR)
stdin stdout
cmd lt inputfile
cmd gt outputfile Numbered file descriptors
0 stdin used by function scanf() 1 stdout used by function printf() 2 stderr hellip
Pipes and InputOutput Redirection
When a file descriptor is assigned to something other than a terminal it is called IO redirection
A file (the contents of the file are fed to a program as if you typed it) wc lt text_file
A pipe (the output of another program is fed as input as if you typed it) The shell can attach things other than your screen to standard output
A file (the output of a program is stored in file) ls gt lsout (gtgt for append)
A pipe (the output of a program is fed as input to another program)
Pipes
cmd1 | cmd2 | cmd3 IO Redirection
cmd1 lt inputfile gt outputfile specifies the input and output file
cmd1 | cmd2 2gtamp1 | cmd3 redirect stderr(2) to stdout and input it to cmd3
Pipes
A pipe is a holder for a stream of data A pipe can be used to hold the output of one program and feed it to
the input of another Separate 2 commands with the ldquo|rdquo character
prog1prog1 prog2prog2STDOUT STDIN
RedirectionPipe Examples
wc lt test1 ls gt lsout ls gtgt lsout ls | wc
Formatted IO Output printf Input scanf Arguments a format string followed by the arguments
printf (char fmt arg1 arg2 hellip)
scanf (char fmt arg1 arg2 hellip) Arguments for scanf have to be the memory addresses
Formatting Output goes to stdout Input comes from stdin Format String regular string + conversion specification
Start of a format specification Width precision adjustment Between lsquorsquo and the conversion character in order
i) rsquo-rsquo specifies left adjustment of the converted argument
A number the minimum field width1048698 ii) lsquorsquo separates the field width from the precision A number precision
string(max num of characters) floating(num of digits after the decimal point) integer(min num of digits)
1048698 iii) l or h long or short1048698 Example Hello World (12 characters)
printf(ldquosrdquo s) -15s 10s -1510s 1510s
Refer to Chapter 72 Formatted Output1048698 Go to web page httpwwwcpluspluscomreferenceclibrarycstdioprintf for more details
String-based inputoutput
String-based input int sscanf (char str char fmt arg1 arg2 hellip)
String-based output int sprintf (char str const char format )
Examplechar st[]=ldquo321 433rdquofloat xysscanf(strdquoffrdquoampxampy)result x=321 y=433
char newst[32]sprintf(newstrdquof frdquo y x)result newst=ldquo433321rdquo
Variable length arguments
Variable length arguments A function may be called with a varying number of arguments of varying types
include ltstdarghgt ltstdiohgt a new datatype va_list declare a variable va_list ap
Associated macro functions va_start(ap last)
Initialize ap to be the va_list after the argument last This need to be done before va_arg and va_end
va_arg(ap int) Expand ap to an expression that has typevalue that match int ap moves to the next argument in the variable list
va_end(ap) Cleanup the variable argument list when done
Variable length arguments
includeltstdiohgtincludeltstdarghgtint add(int n )int main() printf(dn add(41234)) printf(dn add(3123))
return 0
int add(int n ) int i sum tmp va_list arg va_start(arg n) for(sum = i = 0 i lt n ++i) tmp = va_arg(arg int) sum += tmp va_end(arg) return sum
Variable length argumentsvoid foo(char fmt ) va_list ap int d char c p s va_start(ap fmt) while (fmt)
switch(fmt++) case s string
s = va_arg(ap char ) printf(string sn s) break
case d int d = va_arg(ap int) printf(int dn d) break
case c char c = va_arg(ap char) printf(char cn c) break
va_end(ap)
File Accesses Files and file descriptors
FILE fp FILE fopen(char name char mode)
Name can be a long path Mode a combination of lsquorrsquo lsquowrsquo lsquoxrsquo or lsquoarsquo
File inputoutput int getc(FILE fp) int putc(int c FILE fp) These works with default stdinstdout
getchar() putchar()
include ldquostdiohrdquoint main() FILE fp=fopen(ldquotesttxtrdquordquorrdquo) int c int n=0 while((c=getc(fp))=EOF) if(c==lsquo$rsquo) n++ printf(ldquofile contains d $nrdquon) fclose(fp)
File Accesses ldquorldquo Open a file for reading The file must
exist wldquo Create an empty file for writing If a file
with the same name already exists its content is erased and the file is treated as a new empty file
aldquo Append to a file Writing operations append data at the end of the file The file is created if it does not exist
r+ldquo Open a file for update both reading and writing The file must exist
w+ldquo Create an empty file for both reading and writing If a file with the same name already exists its content is erased and the file is treated as a new empty file
a+ldquo Open a file for reading and appending
Line-oriented inputoutput
int getline(char line size_t n FILE fp) char fgets(char line size_t n FILE fp)
gets(char line size_t n) buggy never use it char fputs(char line FILE fp) Donrsquot use scanf() before fgets()
Error handling
fprintf(stderr char fmt arg1 arg2 hellip) exit(1) exit with non-zero status ferror(FILE fp) test for any error on fp feof(FILE fp) test for end-of-file perror(char s)
print the error message s to stderr for the last system or library calls
Weeks 8-9 IO
Standard IO (stdin stdout) and Pipes Formatted IO File IO
System Calls System interface to obtain services from the OS include many subsystems
Memory Scheduler FileStorage System Inter-process Communication and Network etc
A popular subsystem File system File descriptors Low level IO File Management Examples
Programs and Standard IO
ProgramProgramStandard Input(STDIN)bullKeyboardbullOutput from another programbullA file
Standard Output(STDOUT)bullScreenbullInput to another programbullA file
Standard Error(STDERR)
stdin stdout
cmd lt inputfile
cmd gt outputfile Numbered file descriptors
0 stdin used by function scanf() 1 stdout used by function printf() 2 stderr hellip
Pipes and InputOutput Redirection
When a file descriptor is assigned to something other than a terminal it is called IO redirection
A file (the contents of the file are fed to a program as if you typed it) wc lt text_file
A pipe (the output of another program is fed as input as if you typed it) The shell can attach things other than your screen to standard output
A file (the output of a program is stored in file) ls gt lsout (gtgt for append)
A pipe (the output of a program is fed as input to another program)
Pipes
cmd1 | cmd2 | cmd3 IO Redirection
cmd1 lt inputfile gt outputfile specifies the input and output file
cmd1 | cmd2 2gtamp1 | cmd3 redirect stderr(2) to stdout and input it to cmd3
Pipes
A pipe is a holder for a stream of data A pipe can be used to hold the output of one program and feed it to
the input of another Separate 2 commands with the ldquo|rdquo character
prog1prog1 prog2prog2STDOUT STDIN
RedirectionPipe Examples
wc lt test1 ls gt lsout ls gtgt lsout ls | wc
Formatted IO Output printf Input scanf Arguments a format string followed by the arguments
printf (char fmt arg1 arg2 hellip)
scanf (char fmt arg1 arg2 hellip) Arguments for scanf have to be the memory addresses
Formatting Output goes to stdout Input comes from stdin Format String regular string + conversion specification
Start of a format specification Width precision adjustment Between lsquorsquo and the conversion character in order
i) rsquo-rsquo specifies left adjustment of the converted argument
A number the minimum field width1048698 ii) lsquorsquo separates the field width from the precision A number precision
string(max num of characters) floating(num of digits after the decimal point) integer(min num of digits)
1048698 iii) l or h long or short1048698 Example Hello World (12 characters)
printf(ldquosrdquo s) -15s 10s -1510s 1510s
Refer to Chapter 72 Formatted Output1048698 Go to web page httpwwwcpluspluscomreferenceclibrarycstdioprintf for more details
String-based inputoutput
String-based input int sscanf (char str char fmt arg1 arg2 hellip)
String-based output int sprintf (char str const char format )
Examplechar st[]=ldquo321 433rdquofloat xysscanf(strdquoffrdquoampxampy)result x=321 y=433
char newst[32]sprintf(newstrdquof frdquo y x)result newst=ldquo433321rdquo
Variable length arguments
Variable length arguments A function may be called with a varying number of arguments of varying types
include ltstdarghgt ltstdiohgt a new datatype va_list declare a variable va_list ap
Associated macro functions va_start(ap last)
Initialize ap to be the va_list after the argument last This need to be done before va_arg and va_end
va_arg(ap int) Expand ap to an expression that has typevalue that match int ap moves to the next argument in the variable list
va_end(ap) Cleanup the variable argument list when done
Variable length arguments
includeltstdiohgtincludeltstdarghgtint add(int n )int main() printf(dn add(41234)) printf(dn add(3123))
return 0
int add(int n ) int i sum tmp va_list arg va_start(arg n) for(sum = i = 0 i lt n ++i) tmp = va_arg(arg int) sum += tmp va_end(arg) return sum
Variable length argumentsvoid foo(char fmt ) va_list ap int d char c p s va_start(ap fmt) while (fmt)
switch(fmt++) case s string
s = va_arg(ap char ) printf(string sn s) break
case d int d = va_arg(ap int) printf(int dn d) break
case c char c = va_arg(ap char) printf(char cn c) break
va_end(ap)
File Accesses Files and file descriptors
FILE fp FILE fopen(char name char mode)
Name can be a long path Mode a combination of lsquorrsquo lsquowrsquo lsquoxrsquo or lsquoarsquo
File inputoutput int getc(FILE fp) int putc(int c FILE fp) These works with default stdinstdout
getchar() putchar()
include ldquostdiohrdquoint main() FILE fp=fopen(ldquotesttxtrdquordquorrdquo) int c int n=0 while((c=getc(fp))=EOF) if(c==lsquo$rsquo) n++ printf(ldquofile contains d $nrdquon) fclose(fp)
File Accesses ldquorldquo Open a file for reading The file must
exist wldquo Create an empty file for writing If a file
with the same name already exists its content is erased and the file is treated as a new empty file
aldquo Append to a file Writing operations append data at the end of the file The file is created if it does not exist
r+ldquo Open a file for update both reading and writing The file must exist
w+ldquo Create an empty file for both reading and writing If a file with the same name already exists its content is erased and the file is treated as a new empty file
a+ldquo Open a file for reading and appending
Line-oriented inputoutput
int getline(char line size_t n FILE fp) char fgets(char line size_t n FILE fp)
gets(char line size_t n) buggy never use it char fputs(char line FILE fp) Donrsquot use scanf() before fgets()
Error handling
fprintf(stderr char fmt arg1 arg2 hellip) exit(1) exit with non-zero status ferror(FILE fp) test for any error on fp feof(FILE fp) test for end-of-file perror(char s)
print the error message s to stderr for the last system or library calls
Programs and Standard IO
ProgramProgramStandard Input(STDIN)bullKeyboardbullOutput from another programbullA file
Standard Output(STDOUT)bullScreenbullInput to another programbullA file
Standard Error(STDERR)
stdin stdout
cmd lt inputfile
cmd gt outputfile Numbered file descriptors
0 stdin used by function scanf() 1 stdout used by function printf() 2 stderr hellip
Pipes and InputOutput Redirection
When a file descriptor is assigned to something other than a terminal it is called IO redirection
A file (the contents of the file are fed to a program as if you typed it) wc lt text_file
A pipe (the output of another program is fed as input as if you typed it) The shell can attach things other than your screen to standard output
A file (the output of a program is stored in file) ls gt lsout (gtgt for append)
A pipe (the output of a program is fed as input to another program)
Pipes
cmd1 | cmd2 | cmd3 IO Redirection
cmd1 lt inputfile gt outputfile specifies the input and output file
cmd1 | cmd2 2gtamp1 | cmd3 redirect stderr(2) to stdout and input it to cmd3
Pipes
A pipe is a holder for a stream of data A pipe can be used to hold the output of one program and feed it to
the input of another Separate 2 commands with the ldquo|rdquo character
prog1prog1 prog2prog2STDOUT STDIN
RedirectionPipe Examples
wc lt test1 ls gt lsout ls gtgt lsout ls | wc
Formatted IO Output printf Input scanf Arguments a format string followed by the arguments
printf (char fmt arg1 arg2 hellip)
scanf (char fmt arg1 arg2 hellip) Arguments for scanf have to be the memory addresses
Formatting Output goes to stdout Input comes from stdin Format String regular string + conversion specification
Start of a format specification Width precision adjustment Between lsquorsquo and the conversion character in order
i) rsquo-rsquo specifies left adjustment of the converted argument
A number the minimum field width1048698 ii) lsquorsquo separates the field width from the precision A number precision
string(max num of characters) floating(num of digits after the decimal point) integer(min num of digits)
1048698 iii) l or h long or short1048698 Example Hello World (12 characters)
printf(ldquosrdquo s) -15s 10s -1510s 1510s
Refer to Chapter 72 Formatted Output1048698 Go to web page httpwwwcpluspluscomreferenceclibrarycstdioprintf for more details
String-based inputoutput
String-based input int sscanf (char str char fmt arg1 arg2 hellip)
String-based output int sprintf (char str const char format )
Examplechar st[]=ldquo321 433rdquofloat xysscanf(strdquoffrdquoampxampy)result x=321 y=433
char newst[32]sprintf(newstrdquof frdquo y x)result newst=ldquo433321rdquo
Variable length arguments
Variable length arguments A function may be called with a varying number of arguments of varying types
include ltstdarghgt ltstdiohgt a new datatype va_list declare a variable va_list ap
Associated macro functions va_start(ap last)
Initialize ap to be the va_list after the argument last This need to be done before va_arg and va_end
va_arg(ap int) Expand ap to an expression that has typevalue that match int ap moves to the next argument in the variable list
va_end(ap) Cleanup the variable argument list when done
Variable length arguments
includeltstdiohgtincludeltstdarghgtint add(int n )int main() printf(dn add(41234)) printf(dn add(3123))
return 0
int add(int n ) int i sum tmp va_list arg va_start(arg n) for(sum = i = 0 i lt n ++i) tmp = va_arg(arg int) sum += tmp va_end(arg) return sum
Variable length argumentsvoid foo(char fmt ) va_list ap int d char c p s va_start(ap fmt) while (fmt)
switch(fmt++) case s string
s = va_arg(ap char ) printf(string sn s) break
case d int d = va_arg(ap int) printf(int dn d) break
case c char c = va_arg(ap char) printf(char cn c) break
va_end(ap)
File Accesses Files and file descriptors
FILE fp FILE fopen(char name char mode)
Name can be a long path Mode a combination of lsquorrsquo lsquowrsquo lsquoxrsquo or lsquoarsquo
File inputoutput int getc(FILE fp) int putc(int c FILE fp) These works with default stdinstdout
getchar() putchar()
include ldquostdiohrdquoint main() FILE fp=fopen(ldquotesttxtrdquordquorrdquo) int c int n=0 while((c=getc(fp))=EOF) if(c==lsquo$rsquo) n++ printf(ldquofile contains d $nrdquon) fclose(fp)
File Accesses ldquorldquo Open a file for reading The file must
exist wldquo Create an empty file for writing If a file
with the same name already exists its content is erased and the file is treated as a new empty file
aldquo Append to a file Writing operations append data at the end of the file The file is created if it does not exist
r+ldquo Open a file for update both reading and writing The file must exist
w+ldquo Create an empty file for both reading and writing If a file with the same name already exists its content is erased and the file is treated as a new empty file
a+ldquo Open a file for reading and appending
Line-oriented inputoutput
int getline(char line size_t n FILE fp) char fgets(char line size_t n FILE fp)
gets(char line size_t n) buggy never use it char fputs(char line FILE fp) Donrsquot use scanf() before fgets()
Error handling
fprintf(stderr char fmt arg1 arg2 hellip) exit(1) exit with non-zero status ferror(FILE fp) test for any error on fp feof(FILE fp) test for end-of-file perror(char s)
print the error message s to stderr for the last system or library calls
Pipes and InputOutput Redirection
When a file descriptor is assigned to something other than a terminal it is called IO redirection
A file (the contents of the file are fed to a program as if you typed it) wc lt text_file
A pipe (the output of another program is fed as input as if you typed it) The shell can attach things other than your screen to standard output
A file (the output of a program is stored in file) ls gt lsout (gtgt for append)
A pipe (the output of a program is fed as input to another program)
Pipes
cmd1 | cmd2 | cmd3 IO Redirection
cmd1 lt inputfile gt outputfile specifies the input and output file
cmd1 | cmd2 2gtamp1 | cmd3 redirect stderr(2) to stdout and input it to cmd3
Pipes
A pipe is a holder for a stream of data A pipe can be used to hold the output of one program and feed it to
the input of another Separate 2 commands with the ldquo|rdquo character
prog1prog1 prog2prog2STDOUT STDIN
RedirectionPipe Examples
wc lt test1 ls gt lsout ls gtgt lsout ls | wc
Formatted IO Output printf Input scanf Arguments a format string followed by the arguments
printf (char fmt arg1 arg2 hellip)
scanf (char fmt arg1 arg2 hellip) Arguments for scanf have to be the memory addresses
Formatting Output goes to stdout Input comes from stdin Format String regular string + conversion specification
Start of a format specification Width precision adjustment Between lsquorsquo and the conversion character in order
i) rsquo-rsquo specifies left adjustment of the converted argument
A number the minimum field width1048698 ii) lsquorsquo separates the field width from the precision A number precision
string(max num of characters) floating(num of digits after the decimal point) integer(min num of digits)
1048698 iii) l or h long or short1048698 Example Hello World (12 characters)
printf(ldquosrdquo s) -15s 10s -1510s 1510s
Refer to Chapter 72 Formatted Output1048698 Go to web page httpwwwcpluspluscomreferenceclibrarycstdioprintf for more details
String-based inputoutput
String-based input int sscanf (char str char fmt arg1 arg2 hellip)
String-based output int sprintf (char str const char format )
Examplechar st[]=ldquo321 433rdquofloat xysscanf(strdquoffrdquoampxampy)result x=321 y=433
char newst[32]sprintf(newstrdquof frdquo y x)result newst=ldquo433321rdquo
Variable length arguments
Variable length arguments A function may be called with a varying number of arguments of varying types
include ltstdarghgt ltstdiohgt a new datatype va_list declare a variable va_list ap
Associated macro functions va_start(ap last)
Initialize ap to be the va_list after the argument last This need to be done before va_arg and va_end
va_arg(ap int) Expand ap to an expression that has typevalue that match int ap moves to the next argument in the variable list
va_end(ap) Cleanup the variable argument list when done
Variable length arguments
includeltstdiohgtincludeltstdarghgtint add(int n )int main() printf(dn add(41234)) printf(dn add(3123))
return 0
int add(int n ) int i sum tmp va_list arg va_start(arg n) for(sum = i = 0 i lt n ++i) tmp = va_arg(arg int) sum += tmp va_end(arg) return sum
Variable length argumentsvoid foo(char fmt ) va_list ap int d char c p s va_start(ap fmt) while (fmt)
switch(fmt++) case s string
s = va_arg(ap char ) printf(string sn s) break
case d int d = va_arg(ap int) printf(int dn d) break
case c char c = va_arg(ap char) printf(char cn c) break
va_end(ap)
File Accesses Files and file descriptors
FILE fp FILE fopen(char name char mode)
Name can be a long path Mode a combination of lsquorrsquo lsquowrsquo lsquoxrsquo or lsquoarsquo
File inputoutput int getc(FILE fp) int putc(int c FILE fp) These works with default stdinstdout
getchar() putchar()
include ldquostdiohrdquoint main() FILE fp=fopen(ldquotesttxtrdquordquorrdquo) int c int n=0 while((c=getc(fp))=EOF) if(c==lsquo$rsquo) n++ printf(ldquofile contains d $nrdquon) fclose(fp)
File Accesses ldquorldquo Open a file for reading The file must
exist wldquo Create an empty file for writing If a file
with the same name already exists its content is erased and the file is treated as a new empty file
aldquo Append to a file Writing operations append data at the end of the file The file is created if it does not exist
r+ldquo Open a file for update both reading and writing The file must exist
w+ldquo Create an empty file for both reading and writing If a file with the same name already exists its content is erased and the file is treated as a new empty file
a+ldquo Open a file for reading and appending
Line-oriented inputoutput
int getline(char line size_t n FILE fp) char fgets(char line size_t n FILE fp)
gets(char line size_t n) buggy never use it char fputs(char line FILE fp) Donrsquot use scanf() before fgets()
Error handling
fprintf(stderr char fmt arg1 arg2 hellip) exit(1) exit with non-zero status ferror(FILE fp) test for any error on fp feof(FILE fp) test for end-of-file perror(char s)
print the error message s to stderr for the last system or library calls
Pipes
A pipe is a holder for a stream of data A pipe can be used to hold the output of one program and feed it to
the input of another Separate 2 commands with the ldquo|rdquo character
prog1prog1 prog2prog2STDOUT STDIN
RedirectionPipe Examples
wc lt test1 ls gt lsout ls gtgt lsout ls | wc
Formatted IO Output printf Input scanf Arguments a format string followed by the arguments
printf (char fmt arg1 arg2 hellip)
scanf (char fmt arg1 arg2 hellip) Arguments for scanf have to be the memory addresses
Formatting Output goes to stdout Input comes from stdin Format String regular string + conversion specification
Start of a format specification Width precision adjustment Between lsquorsquo and the conversion character in order
i) rsquo-rsquo specifies left adjustment of the converted argument
A number the minimum field width1048698 ii) lsquorsquo separates the field width from the precision A number precision
string(max num of characters) floating(num of digits after the decimal point) integer(min num of digits)
1048698 iii) l or h long or short1048698 Example Hello World (12 characters)
printf(ldquosrdquo s) -15s 10s -1510s 1510s
Refer to Chapter 72 Formatted Output1048698 Go to web page httpwwwcpluspluscomreferenceclibrarycstdioprintf for more details
String-based inputoutput
String-based input int sscanf (char str char fmt arg1 arg2 hellip)
String-based output int sprintf (char str const char format )
Examplechar st[]=ldquo321 433rdquofloat xysscanf(strdquoffrdquoampxampy)result x=321 y=433
char newst[32]sprintf(newstrdquof frdquo y x)result newst=ldquo433321rdquo
Variable length arguments
Variable length arguments A function may be called with a varying number of arguments of varying types
include ltstdarghgt ltstdiohgt a new datatype va_list declare a variable va_list ap
Associated macro functions va_start(ap last)
Initialize ap to be the va_list after the argument last This need to be done before va_arg and va_end
va_arg(ap int) Expand ap to an expression that has typevalue that match int ap moves to the next argument in the variable list
va_end(ap) Cleanup the variable argument list when done
Variable length arguments
includeltstdiohgtincludeltstdarghgtint add(int n )int main() printf(dn add(41234)) printf(dn add(3123))
return 0
int add(int n ) int i sum tmp va_list arg va_start(arg n) for(sum = i = 0 i lt n ++i) tmp = va_arg(arg int) sum += tmp va_end(arg) return sum
Variable length argumentsvoid foo(char fmt ) va_list ap int d char c p s va_start(ap fmt) while (fmt)
switch(fmt++) case s string
s = va_arg(ap char ) printf(string sn s) break
case d int d = va_arg(ap int) printf(int dn d) break
case c char c = va_arg(ap char) printf(char cn c) break
va_end(ap)
File Accesses Files and file descriptors
FILE fp FILE fopen(char name char mode)
Name can be a long path Mode a combination of lsquorrsquo lsquowrsquo lsquoxrsquo or lsquoarsquo
File inputoutput int getc(FILE fp) int putc(int c FILE fp) These works with default stdinstdout
getchar() putchar()
include ldquostdiohrdquoint main() FILE fp=fopen(ldquotesttxtrdquordquorrdquo) int c int n=0 while((c=getc(fp))=EOF) if(c==lsquo$rsquo) n++ printf(ldquofile contains d $nrdquon) fclose(fp)
File Accesses ldquorldquo Open a file for reading The file must
exist wldquo Create an empty file for writing If a file
with the same name already exists its content is erased and the file is treated as a new empty file
aldquo Append to a file Writing operations append data at the end of the file The file is created if it does not exist
r+ldquo Open a file for update both reading and writing The file must exist
w+ldquo Create an empty file for both reading and writing If a file with the same name already exists its content is erased and the file is treated as a new empty file
a+ldquo Open a file for reading and appending
Line-oriented inputoutput
int getline(char line size_t n FILE fp) char fgets(char line size_t n FILE fp)
gets(char line size_t n) buggy never use it char fputs(char line FILE fp) Donrsquot use scanf() before fgets()
Error handling
fprintf(stderr char fmt arg1 arg2 hellip) exit(1) exit with non-zero status ferror(FILE fp) test for any error on fp feof(FILE fp) test for end-of-file perror(char s)
print the error message s to stderr for the last system or library calls
RedirectionPipe Examples
wc lt test1 ls gt lsout ls gtgt lsout ls | wc
Formatted IO Output printf Input scanf Arguments a format string followed by the arguments
printf (char fmt arg1 arg2 hellip)
scanf (char fmt arg1 arg2 hellip) Arguments for scanf have to be the memory addresses
Formatting Output goes to stdout Input comes from stdin Format String regular string + conversion specification
Start of a format specification Width precision adjustment Between lsquorsquo and the conversion character in order
i) rsquo-rsquo specifies left adjustment of the converted argument
A number the minimum field width1048698 ii) lsquorsquo separates the field width from the precision A number precision
string(max num of characters) floating(num of digits after the decimal point) integer(min num of digits)
1048698 iii) l or h long or short1048698 Example Hello World (12 characters)
printf(ldquosrdquo s) -15s 10s -1510s 1510s
Refer to Chapter 72 Formatted Output1048698 Go to web page httpwwwcpluspluscomreferenceclibrarycstdioprintf for more details
String-based inputoutput
String-based input int sscanf (char str char fmt arg1 arg2 hellip)
String-based output int sprintf (char str const char format )
Examplechar st[]=ldquo321 433rdquofloat xysscanf(strdquoffrdquoampxampy)result x=321 y=433
char newst[32]sprintf(newstrdquof frdquo y x)result newst=ldquo433321rdquo
Variable length arguments
Variable length arguments A function may be called with a varying number of arguments of varying types
include ltstdarghgt ltstdiohgt a new datatype va_list declare a variable va_list ap
Associated macro functions va_start(ap last)
Initialize ap to be the va_list after the argument last This need to be done before va_arg and va_end
va_arg(ap int) Expand ap to an expression that has typevalue that match int ap moves to the next argument in the variable list
va_end(ap) Cleanup the variable argument list when done
Variable length arguments
includeltstdiohgtincludeltstdarghgtint add(int n )int main() printf(dn add(41234)) printf(dn add(3123))
return 0
int add(int n ) int i sum tmp va_list arg va_start(arg n) for(sum = i = 0 i lt n ++i) tmp = va_arg(arg int) sum += tmp va_end(arg) return sum
Variable length argumentsvoid foo(char fmt ) va_list ap int d char c p s va_start(ap fmt) while (fmt)
switch(fmt++) case s string
s = va_arg(ap char ) printf(string sn s) break
case d int d = va_arg(ap int) printf(int dn d) break
case c char c = va_arg(ap char) printf(char cn c) break
va_end(ap)
File Accesses Files and file descriptors
FILE fp FILE fopen(char name char mode)
Name can be a long path Mode a combination of lsquorrsquo lsquowrsquo lsquoxrsquo or lsquoarsquo
File inputoutput int getc(FILE fp) int putc(int c FILE fp) These works with default stdinstdout
getchar() putchar()
include ldquostdiohrdquoint main() FILE fp=fopen(ldquotesttxtrdquordquorrdquo) int c int n=0 while((c=getc(fp))=EOF) if(c==lsquo$rsquo) n++ printf(ldquofile contains d $nrdquon) fclose(fp)
File Accesses ldquorldquo Open a file for reading The file must
exist wldquo Create an empty file for writing If a file
with the same name already exists its content is erased and the file is treated as a new empty file
aldquo Append to a file Writing operations append data at the end of the file The file is created if it does not exist
r+ldquo Open a file for update both reading and writing The file must exist
w+ldquo Create an empty file for both reading and writing If a file with the same name already exists its content is erased and the file is treated as a new empty file
a+ldquo Open a file for reading and appending
Line-oriented inputoutput
int getline(char line size_t n FILE fp) char fgets(char line size_t n FILE fp)
gets(char line size_t n) buggy never use it char fputs(char line FILE fp) Donrsquot use scanf() before fgets()
Error handling
fprintf(stderr char fmt arg1 arg2 hellip) exit(1) exit with non-zero status ferror(FILE fp) test for any error on fp feof(FILE fp) test for end-of-file perror(char s)
print the error message s to stderr for the last system or library calls
Formatted IO Output printf Input scanf Arguments a format string followed by the arguments
printf (char fmt arg1 arg2 hellip)
scanf (char fmt arg1 arg2 hellip) Arguments for scanf have to be the memory addresses
Formatting Output goes to stdout Input comes from stdin Format String regular string + conversion specification
Start of a format specification Width precision adjustment Between lsquorsquo and the conversion character in order
i) rsquo-rsquo specifies left adjustment of the converted argument
A number the minimum field width1048698 ii) lsquorsquo separates the field width from the precision A number precision
string(max num of characters) floating(num of digits after the decimal point) integer(min num of digits)
1048698 iii) l or h long or short1048698 Example Hello World (12 characters)
printf(ldquosrdquo s) -15s 10s -1510s 1510s
Refer to Chapter 72 Formatted Output1048698 Go to web page httpwwwcpluspluscomreferenceclibrarycstdioprintf for more details
String-based inputoutput
String-based input int sscanf (char str char fmt arg1 arg2 hellip)
String-based output int sprintf (char str const char format )
Examplechar st[]=ldquo321 433rdquofloat xysscanf(strdquoffrdquoampxampy)result x=321 y=433
char newst[32]sprintf(newstrdquof frdquo y x)result newst=ldquo433321rdquo
Variable length arguments
Variable length arguments A function may be called with a varying number of arguments of varying types
include ltstdarghgt ltstdiohgt a new datatype va_list declare a variable va_list ap
Associated macro functions va_start(ap last)
Initialize ap to be the va_list after the argument last This need to be done before va_arg and va_end
va_arg(ap int) Expand ap to an expression that has typevalue that match int ap moves to the next argument in the variable list
va_end(ap) Cleanup the variable argument list when done
Variable length arguments
includeltstdiohgtincludeltstdarghgtint add(int n )int main() printf(dn add(41234)) printf(dn add(3123))
return 0
int add(int n ) int i sum tmp va_list arg va_start(arg n) for(sum = i = 0 i lt n ++i) tmp = va_arg(arg int) sum += tmp va_end(arg) return sum
Variable length argumentsvoid foo(char fmt ) va_list ap int d char c p s va_start(ap fmt) while (fmt)
switch(fmt++) case s string
s = va_arg(ap char ) printf(string sn s) break
case d int d = va_arg(ap int) printf(int dn d) break
case c char c = va_arg(ap char) printf(char cn c) break
va_end(ap)
File Accesses Files and file descriptors
FILE fp FILE fopen(char name char mode)
Name can be a long path Mode a combination of lsquorrsquo lsquowrsquo lsquoxrsquo or lsquoarsquo
File inputoutput int getc(FILE fp) int putc(int c FILE fp) These works with default stdinstdout
getchar() putchar()
include ldquostdiohrdquoint main() FILE fp=fopen(ldquotesttxtrdquordquorrdquo) int c int n=0 while((c=getc(fp))=EOF) if(c==lsquo$rsquo) n++ printf(ldquofile contains d $nrdquon) fclose(fp)
File Accesses ldquorldquo Open a file for reading The file must
exist wldquo Create an empty file for writing If a file
with the same name already exists its content is erased and the file is treated as a new empty file
aldquo Append to a file Writing operations append data at the end of the file The file is created if it does not exist
r+ldquo Open a file for update both reading and writing The file must exist
w+ldquo Create an empty file for both reading and writing If a file with the same name already exists its content is erased and the file is treated as a new empty file
a+ldquo Open a file for reading and appending
Line-oriented inputoutput
int getline(char line size_t n FILE fp) char fgets(char line size_t n FILE fp)
gets(char line size_t n) buggy never use it char fputs(char line FILE fp) Donrsquot use scanf() before fgets()
Error handling
fprintf(stderr char fmt arg1 arg2 hellip) exit(1) exit with non-zero status ferror(FILE fp) test for any error on fp feof(FILE fp) test for end-of-file perror(char s)
print the error message s to stderr for the last system or library calls
Formatting Output goes to stdout Input comes from stdin Format String regular string + conversion specification
Start of a format specification Width precision adjustment Between lsquorsquo and the conversion character in order
i) rsquo-rsquo specifies left adjustment of the converted argument
A number the minimum field width1048698 ii) lsquorsquo separates the field width from the precision A number precision
string(max num of characters) floating(num of digits after the decimal point) integer(min num of digits)
1048698 iii) l or h long or short1048698 Example Hello World (12 characters)
printf(ldquosrdquo s) -15s 10s -1510s 1510s
Refer to Chapter 72 Formatted Output1048698 Go to web page httpwwwcpluspluscomreferenceclibrarycstdioprintf for more details
String-based inputoutput
String-based input int sscanf (char str char fmt arg1 arg2 hellip)
String-based output int sprintf (char str const char format )
Examplechar st[]=ldquo321 433rdquofloat xysscanf(strdquoffrdquoampxampy)result x=321 y=433
char newst[32]sprintf(newstrdquof frdquo y x)result newst=ldquo433321rdquo
Variable length arguments
Variable length arguments A function may be called with a varying number of arguments of varying types
include ltstdarghgt ltstdiohgt a new datatype va_list declare a variable va_list ap
Associated macro functions va_start(ap last)
Initialize ap to be the va_list after the argument last This need to be done before va_arg and va_end
va_arg(ap int) Expand ap to an expression that has typevalue that match int ap moves to the next argument in the variable list
va_end(ap) Cleanup the variable argument list when done
Variable length arguments
includeltstdiohgtincludeltstdarghgtint add(int n )int main() printf(dn add(41234)) printf(dn add(3123))
return 0
int add(int n ) int i sum tmp va_list arg va_start(arg n) for(sum = i = 0 i lt n ++i) tmp = va_arg(arg int) sum += tmp va_end(arg) return sum
Variable length argumentsvoid foo(char fmt ) va_list ap int d char c p s va_start(ap fmt) while (fmt)
switch(fmt++) case s string
s = va_arg(ap char ) printf(string sn s) break
case d int d = va_arg(ap int) printf(int dn d) break
case c char c = va_arg(ap char) printf(char cn c) break
va_end(ap)
File Accesses Files and file descriptors
FILE fp FILE fopen(char name char mode)
Name can be a long path Mode a combination of lsquorrsquo lsquowrsquo lsquoxrsquo or lsquoarsquo
File inputoutput int getc(FILE fp) int putc(int c FILE fp) These works with default stdinstdout
getchar() putchar()
include ldquostdiohrdquoint main() FILE fp=fopen(ldquotesttxtrdquordquorrdquo) int c int n=0 while((c=getc(fp))=EOF) if(c==lsquo$rsquo) n++ printf(ldquofile contains d $nrdquon) fclose(fp)
File Accesses ldquorldquo Open a file for reading The file must
exist wldquo Create an empty file for writing If a file
with the same name already exists its content is erased and the file is treated as a new empty file
aldquo Append to a file Writing operations append data at the end of the file The file is created if it does not exist
r+ldquo Open a file for update both reading and writing The file must exist
w+ldquo Create an empty file for both reading and writing If a file with the same name already exists its content is erased and the file is treated as a new empty file
a+ldquo Open a file for reading and appending
Line-oriented inputoutput
int getline(char line size_t n FILE fp) char fgets(char line size_t n FILE fp)
gets(char line size_t n) buggy never use it char fputs(char line FILE fp) Donrsquot use scanf() before fgets()
Error handling
fprintf(stderr char fmt arg1 arg2 hellip) exit(1) exit with non-zero status ferror(FILE fp) test for any error on fp feof(FILE fp) test for end-of-file perror(char s)
print the error message s to stderr for the last system or library calls
String-based inputoutput
String-based input int sscanf (char str char fmt arg1 arg2 hellip)
String-based output int sprintf (char str const char format )
Examplechar st[]=ldquo321 433rdquofloat xysscanf(strdquoffrdquoampxampy)result x=321 y=433
char newst[32]sprintf(newstrdquof frdquo y x)result newst=ldquo433321rdquo
Variable length arguments
Variable length arguments A function may be called with a varying number of arguments of varying types
include ltstdarghgt ltstdiohgt a new datatype va_list declare a variable va_list ap
Associated macro functions va_start(ap last)
Initialize ap to be the va_list after the argument last This need to be done before va_arg and va_end
va_arg(ap int) Expand ap to an expression that has typevalue that match int ap moves to the next argument in the variable list
va_end(ap) Cleanup the variable argument list when done
Variable length arguments
includeltstdiohgtincludeltstdarghgtint add(int n )int main() printf(dn add(41234)) printf(dn add(3123))
return 0
int add(int n ) int i sum tmp va_list arg va_start(arg n) for(sum = i = 0 i lt n ++i) tmp = va_arg(arg int) sum += tmp va_end(arg) return sum
Variable length argumentsvoid foo(char fmt ) va_list ap int d char c p s va_start(ap fmt) while (fmt)
switch(fmt++) case s string
s = va_arg(ap char ) printf(string sn s) break
case d int d = va_arg(ap int) printf(int dn d) break
case c char c = va_arg(ap char) printf(char cn c) break
va_end(ap)
File Accesses Files and file descriptors
FILE fp FILE fopen(char name char mode)
Name can be a long path Mode a combination of lsquorrsquo lsquowrsquo lsquoxrsquo or lsquoarsquo
File inputoutput int getc(FILE fp) int putc(int c FILE fp) These works with default stdinstdout
getchar() putchar()
include ldquostdiohrdquoint main() FILE fp=fopen(ldquotesttxtrdquordquorrdquo) int c int n=0 while((c=getc(fp))=EOF) if(c==lsquo$rsquo) n++ printf(ldquofile contains d $nrdquon) fclose(fp)
File Accesses ldquorldquo Open a file for reading The file must
exist wldquo Create an empty file for writing If a file
with the same name already exists its content is erased and the file is treated as a new empty file
aldquo Append to a file Writing operations append data at the end of the file The file is created if it does not exist
r+ldquo Open a file for update both reading and writing The file must exist
w+ldquo Create an empty file for both reading and writing If a file with the same name already exists its content is erased and the file is treated as a new empty file
a+ldquo Open a file for reading and appending
Line-oriented inputoutput
int getline(char line size_t n FILE fp) char fgets(char line size_t n FILE fp)
gets(char line size_t n) buggy never use it char fputs(char line FILE fp) Donrsquot use scanf() before fgets()
Error handling
fprintf(stderr char fmt arg1 arg2 hellip) exit(1) exit with non-zero status ferror(FILE fp) test for any error on fp feof(FILE fp) test for end-of-file perror(char s)
print the error message s to stderr for the last system or library calls
Variable length arguments
Variable length arguments A function may be called with a varying number of arguments of varying types
include ltstdarghgt ltstdiohgt a new datatype va_list declare a variable va_list ap
Associated macro functions va_start(ap last)
Initialize ap to be the va_list after the argument last This need to be done before va_arg and va_end
va_arg(ap int) Expand ap to an expression that has typevalue that match int ap moves to the next argument in the variable list
va_end(ap) Cleanup the variable argument list when done
Variable length arguments
includeltstdiohgtincludeltstdarghgtint add(int n )int main() printf(dn add(41234)) printf(dn add(3123))
return 0
int add(int n ) int i sum tmp va_list arg va_start(arg n) for(sum = i = 0 i lt n ++i) tmp = va_arg(arg int) sum += tmp va_end(arg) return sum
Variable length argumentsvoid foo(char fmt ) va_list ap int d char c p s va_start(ap fmt) while (fmt)
switch(fmt++) case s string
s = va_arg(ap char ) printf(string sn s) break
case d int d = va_arg(ap int) printf(int dn d) break
case c char c = va_arg(ap char) printf(char cn c) break
va_end(ap)
File Accesses Files and file descriptors
FILE fp FILE fopen(char name char mode)
Name can be a long path Mode a combination of lsquorrsquo lsquowrsquo lsquoxrsquo or lsquoarsquo
File inputoutput int getc(FILE fp) int putc(int c FILE fp) These works with default stdinstdout
getchar() putchar()
include ldquostdiohrdquoint main() FILE fp=fopen(ldquotesttxtrdquordquorrdquo) int c int n=0 while((c=getc(fp))=EOF) if(c==lsquo$rsquo) n++ printf(ldquofile contains d $nrdquon) fclose(fp)
File Accesses ldquorldquo Open a file for reading The file must
exist wldquo Create an empty file for writing If a file
with the same name already exists its content is erased and the file is treated as a new empty file
aldquo Append to a file Writing operations append data at the end of the file The file is created if it does not exist
r+ldquo Open a file for update both reading and writing The file must exist
w+ldquo Create an empty file for both reading and writing If a file with the same name already exists its content is erased and the file is treated as a new empty file
a+ldquo Open a file for reading and appending
Line-oriented inputoutput
int getline(char line size_t n FILE fp) char fgets(char line size_t n FILE fp)
gets(char line size_t n) buggy never use it char fputs(char line FILE fp) Donrsquot use scanf() before fgets()
Error handling
fprintf(stderr char fmt arg1 arg2 hellip) exit(1) exit with non-zero status ferror(FILE fp) test for any error on fp feof(FILE fp) test for end-of-file perror(char s)
print the error message s to stderr for the last system or library calls
Variable length arguments
includeltstdiohgtincludeltstdarghgtint add(int n )int main() printf(dn add(41234)) printf(dn add(3123))
return 0
int add(int n ) int i sum tmp va_list arg va_start(arg n) for(sum = i = 0 i lt n ++i) tmp = va_arg(arg int) sum += tmp va_end(arg) return sum
Variable length argumentsvoid foo(char fmt ) va_list ap int d char c p s va_start(ap fmt) while (fmt)
switch(fmt++) case s string
s = va_arg(ap char ) printf(string sn s) break
case d int d = va_arg(ap int) printf(int dn d) break
case c char c = va_arg(ap char) printf(char cn c) break
va_end(ap)
File Accesses Files and file descriptors
FILE fp FILE fopen(char name char mode)
Name can be a long path Mode a combination of lsquorrsquo lsquowrsquo lsquoxrsquo or lsquoarsquo
File inputoutput int getc(FILE fp) int putc(int c FILE fp) These works with default stdinstdout
getchar() putchar()
include ldquostdiohrdquoint main() FILE fp=fopen(ldquotesttxtrdquordquorrdquo) int c int n=0 while((c=getc(fp))=EOF) if(c==lsquo$rsquo) n++ printf(ldquofile contains d $nrdquon) fclose(fp)
File Accesses ldquorldquo Open a file for reading The file must
exist wldquo Create an empty file for writing If a file
with the same name already exists its content is erased and the file is treated as a new empty file
aldquo Append to a file Writing operations append data at the end of the file The file is created if it does not exist
r+ldquo Open a file for update both reading and writing The file must exist
w+ldquo Create an empty file for both reading and writing If a file with the same name already exists its content is erased and the file is treated as a new empty file
a+ldquo Open a file for reading and appending
Line-oriented inputoutput
int getline(char line size_t n FILE fp) char fgets(char line size_t n FILE fp)
gets(char line size_t n) buggy never use it char fputs(char line FILE fp) Donrsquot use scanf() before fgets()
Error handling
fprintf(stderr char fmt arg1 arg2 hellip) exit(1) exit with non-zero status ferror(FILE fp) test for any error on fp feof(FILE fp) test for end-of-file perror(char s)
print the error message s to stderr for the last system or library calls
Variable length argumentsvoid foo(char fmt ) va_list ap int d char c p s va_start(ap fmt) while (fmt)
switch(fmt++) case s string
s = va_arg(ap char ) printf(string sn s) break
case d int d = va_arg(ap int) printf(int dn d) break
case c char c = va_arg(ap char) printf(char cn c) break
va_end(ap)
File Accesses Files and file descriptors
FILE fp FILE fopen(char name char mode)
Name can be a long path Mode a combination of lsquorrsquo lsquowrsquo lsquoxrsquo or lsquoarsquo
File inputoutput int getc(FILE fp) int putc(int c FILE fp) These works with default stdinstdout
getchar() putchar()
include ldquostdiohrdquoint main() FILE fp=fopen(ldquotesttxtrdquordquorrdquo) int c int n=0 while((c=getc(fp))=EOF) if(c==lsquo$rsquo) n++ printf(ldquofile contains d $nrdquon) fclose(fp)
File Accesses ldquorldquo Open a file for reading The file must
exist wldquo Create an empty file for writing If a file
with the same name already exists its content is erased and the file is treated as a new empty file
aldquo Append to a file Writing operations append data at the end of the file The file is created if it does not exist
r+ldquo Open a file for update both reading and writing The file must exist
w+ldquo Create an empty file for both reading and writing If a file with the same name already exists its content is erased and the file is treated as a new empty file
a+ldquo Open a file for reading and appending
Line-oriented inputoutput
int getline(char line size_t n FILE fp) char fgets(char line size_t n FILE fp)
gets(char line size_t n) buggy never use it char fputs(char line FILE fp) Donrsquot use scanf() before fgets()
Error handling
fprintf(stderr char fmt arg1 arg2 hellip) exit(1) exit with non-zero status ferror(FILE fp) test for any error on fp feof(FILE fp) test for end-of-file perror(char s)
print the error message s to stderr for the last system or library calls
File Accesses Files and file descriptors
FILE fp FILE fopen(char name char mode)
Name can be a long path Mode a combination of lsquorrsquo lsquowrsquo lsquoxrsquo or lsquoarsquo
File inputoutput int getc(FILE fp) int putc(int c FILE fp) These works with default stdinstdout
getchar() putchar()
include ldquostdiohrdquoint main() FILE fp=fopen(ldquotesttxtrdquordquorrdquo) int c int n=0 while((c=getc(fp))=EOF) if(c==lsquo$rsquo) n++ printf(ldquofile contains d $nrdquon) fclose(fp)
File Accesses ldquorldquo Open a file for reading The file must
exist wldquo Create an empty file for writing If a file
with the same name already exists its content is erased and the file is treated as a new empty file
aldquo Append to a file Writing operations append data at the end of the file The file is created if it does not exist
r+ldquo Open a file for update both reading and writing The file must exist
w+ldquo Create an empty file for both reading and writing If a file with the same name already exists its content is erased and the file is treated as a new empty file
a+ldquo Open a file for reading and appending
Line-oriented inputoutput
int getline(char line size_t n FILE fp) char fgets(char line size_t n FILE fp)
gets(char line size_t n) buggy never use it char fputs(char line FILE fp) Donrsquot use scanf() before fgets()
Error handling
fprintf(stderr char fmt arg1 arg2 hellip) exit(1) exit with non-zero status ferror(FILE fp) test for any error on fp feof(FILE fp) test for end-of-file perror(char s)
print the error message s to stderr for the last system or library calls
File Accesses ldquorldquo Open a file for reading The file must
exist wldquo Create an empty file for writing If a file
with the same name already exists its content is erased and the file is treated as a new empty file
aldquo Append to a file Writing operations append data at the end of the file The file is created if it does not exist
r+ldquo Open a file for update both reading and writing The file must exist
w+ldquo Create an empty file for both reading and writing If a file with the same name already exists its content is erased and the file is treated as a new empty file
a+ldquo Open a file for reading and appending
Line-oriented inputoutput
int getline(char line size_t n FILE fp) char fgets(char line size_t n FILE fp)
gets(char line size_t n) buggy never use it char fputs(char line FILE fp) Donrsquot use scanf() before fgets()
Error handling
fprintf(stderr char fmt arg1 arg2 hellip) exit(1) exit with non-zero status ferror(FILE fp) test for any error on fp feof(FILE fp) test for end-of-file perror(char s)
print the error message s to stderr for the last system or library calls
Line-oriented inputoutput
int getline(char line size_t n FILE fp) char fgets(char line size_t n FILE fp)
gets(char line size_t n) buggy never use it char fputs(char line FILE fp) Donrsquot use scanf() before fgets()
Error handling
fprintf(stderr char fmt arg1 arg2 hellip) exit(1) exit with non-zero status ferror(FILE fp) test for any error on fp feof(FILE fp) test for end-of-file perror(char s)
print the error message s to stderr for the last system or library calls
Error handling
fprintf(stderr char fmt arg1 arg2 hellip) exit(1) exit with non-zero status ferror(FILE fp) test for any error on fp feof(FILE fp) test for end-of-file perror(char s)
print the error message s to stderr for the last system or library calls