Week 14 Lectures PDF
Week 14 Lectures PDF
Programming
File I/O
• fp = fopen(name, mode);
argv:
echo\0
hello,\0
world\0
0
a two dimensional
array of characters
EE1102 Intro to Comp Prog 22
Implementing echo
#include <stdio.h>
/* echo command line arguments: 1st version */
main(int argc, char *argv[ ]){
int i;
for (i = 1; i < argc; i++)
printf(“%s%s”, argv[i], (i<argc – 1)?
“ ” : “”);
printf(“\n”);
return 0;
} EE1102 Intro to Comp Prog 23
echo – Pointer Version
#include <stdio.h>
/* echo comand line arguments: 2nd version */
main(int argc, char *argv[ ]){
while (--argc > 0)
printf(“%s%s”, *++argv, (argc > 1)? “ ” : “”);
printf(“\n”);
return 0;
}
printf((argc > 1) ? “%s ” : “%s”, *++argv);
EE1102 Intro to Comp Prog 24
cat – Reads Files and Prints Them
#include <stdio.h>
main(int argc, char *argv[ ]){
FILE *fp;
void filecopy(FILE *, FILE *)
if (argc == 1) /* no args; copy from stdin */
filecopy(stdin, stdout);
else
/*open the first file, copy it onto screen,
close it, go to next file …. */
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
EE1102 Intro to Comp Prog 30