Upload
veda-campos
View
12
Download
0
Embed Size (px)
DESCRIPTION
Advanced UNIX. 240-491 Special Topics in Comp. Eng. 1 Semester 2, 2000-2001. Objectives of these slides: look in some detail at standard input and output in C. 9. Standard I/O in C. Overview. 1. Background 2. Formatted Output: printf() 3. Formatted Input: scanf() - PowerPoint PPT Presentation
Citation preview
240-491 Adv. UNIX:io/9 1
Advanced UNIXAdvanced UNIX
Objectives of these slides:Objectives of these slides:– look in some detail at standard input look in some detail at standard input
and output in Cand output in C
240-491 Special Topics in Comp. Eng. 1Semester 2, 2000-2001
9. Standard I/O in C
240-491 Adv. UNIX:io/9 2
OverviewOverview
1. Background1. Background
2. Formatted Output: 2. Formatted Output: printf()printf()
3. Formatted Input: 3. Formatted Input: scanf()scanf()
4. Line I/O: 4. Line I/O: gets()gets(), , puts()puts()
5. Character I/O: 5. Character I/O: getchar()getchar(), , putchar()putchar()
240-491 Adv. UNIX:io/9 3
1. Background1. Background
Most I/O library functions are in Most I/O library functions are in stdio.hstdio.h
Basic methods:Basic methods:– 1. Formatted I/O1. Formatted I/O– 2. Line by line2. Line by line– 3. Character by character3. Character by character
240-491 Adv. UNIX:io/9 4
2. Formatted Output: printf()2. Formatted Output: printf()
int i = 2, j = 7;int i = 2, j = 7;printf(“i = %d, j = %d\n”, i, j);printf(“i = %d, j = %d\n”, i, j);
floatfloat, , doubledouble printed with printed with %f%f, , %e%e, , %g%g::
double x = 3.14;double x = 3.14;printf(“%f, printf(“%f, %e%e, , %g%g\n”, x, x, x);\n”, x, x, x);
3.140000, 3.140000e+00, 3.143.140000, 3.140000e+00, 3.14
6 dp is the default
240-491 Adv. UNIX:io/9 5
Character StringsCharacter Strings
char name[SIZE], ch;char name[SIZE], ch; : :printf(“Hi, there, %s\n”, name);printf(“Hi, there, %s\n”, name);printf(“The letter is printf(“The letter is %c%c \n”, ch); \n”, ch);
See man ascii for some unusual chars, e.g. '\a' '\b' '\r'
240-491 Adv. UNIX:io/9 6
Less Used printf() Format SpecifiersLess Used printf() Format Specifiers
SpecifierSpecifier MeaningMeaning%%%% % character% character%u%u Decimal unsigned integerDecimal unsigned integer%o%o Octal integerOctal integer%x%x Hexadecimal integerHexadecimal integer%p%p Pointer (decimal or hex)Pointer (decimal or hex)%n%n Store the number of charsStore the number of chars
written so farwritten so far
continued
useful forprintingunusualchars, seeman ascii
240-491 Adv. UNIX:io/9 7
ExamplesExamples
int i = 125, num;int i = 125, num;int *p = &i;int *p = &i;
printf(“%d, printf(“%d, %o, %x, %X, %p%n%o, %x, %X, %p%n\n”,\n”,i, i, i, i, p, &num);i, i, i, i, p, &num);
printf(“num = %d\n”, num);printf(“num = %d\n”, num);
125, 175, 7d, 7D, 7fffbe48125, 175, 7d, 7D, 7fffbe48num = 31num = 31
upper casehex letters
the decimal isconverted
240-491 Adv. UNIX:io/9 8
Four Types of Format ModifiersFour Types of Format Modifiers
1. Flags1. Flags– e.g. e.g. "%"%++d"d"
2. Field Widths2. Field Widths– e.g. e.g. "%"%1010d"d"
3. Precision3. Precision– e.g. e.g. "%"%.4.4d"d"
4. Type Modifiers4. Type Modifiers– e.g. e.g. "%"%lld"d"
printf(".....", x, y, z);
format string
240-491 Adv. UNIX:io/9 9
2.1. Flags2.1. Flags
FlagFlag MeaningMeaning++ Prefix positive numbers with a + Prefix positive numbers with a + signsign
spacespace Prefix positive numbers with a spacePrefix positive numbers with a space
00 Pad with leading zerosPad with leading zeros
## Alternate output formAlternate output form
240-491 Adv. UNIX:io/9 10
ExamplesExamples
printf(“%printf(“%++d\n%d\n%++d\n”, 786, -786);d\n”, 786, -786);+786+786-786-786
printf(“% d\n% d\n”, 547, -547);printf(“% d\n% d\n”, 547, -547); 547 547-547-547
printf(“%printf(“%+0+09d\n%9d\n%009d\n”, 452, 452);9d\n”, 452, 452);+00000452+00000452000000452000000452
useful fortidy columns
240-491 Adv. UNIX:io/9 11
Meaning of #Meaning of # Prefix Prefix 00 is added to is added to octaloctal output ( output (%#o%#o).).
Prefix Prefix 0x0x or or 0X0X is added to is added to hexadecimalhexadecimal output output ((%#x%#x or or %#X%#X).).
%#e%#e, , %#f%#f, , %#g%#g have a have a decimaldecimal point, even when point, even when there are no digits after it.there are no digits after it.
%#g%#g does not remove trailing zeros. does not remove trailing zeros.
240-491 Adv. UNIX:io/9 12
int c = 1427;int c = 1427;float p = 1427.0;float p = 1427.0;printf(“%printf(“%##o, %o, %##x, %x, %##X, %g, %X, %g, %##g\n”, g\n”,
c, c, c, p, p);c, c, c, p, p);
02623, 0x593, 0X593, 1427, 1427.0002623, 0x593, 0X593, 1427, 1427.00
# Examples# Examples
octal hex hex remove '.'and 0's
do notremove '.'and 0's
240-491 Adv. UNIX:io/9 13
2.2. Field Widths2.2. Field Widths
Specify minimum number of characters printed:Specify minimum number of characters printed:– if too few characters, right justify outputif too few characters, right justify output
– if too many, ignore field widthif too many, ignore field width
240-491 Adv. UNIX:io/9 14
ExampleExample
char *s = “hello”;char *s = “hello”;int x = 23;int x = 23;printf(“%printf(“%1010d%10s\n”, x, s);d%10s\n”, x, s);printf(“%printf(“%-10-10d%-10s\n”, x, s);d%-10s\n”, x, s);
23 hello 23 hello23 hello23 hello
width
- = leftjustify
10 10
240-491 Adv. UNIX:io/9 15
Field Width (*) in printf()Field Width (*) in printf()
Calculate field width based on the next Calculate field width based on the next printf()printf() argument: argument:
#define FIELD_WIDTH 10#define FIELD_WIDTH 10printf(“%printf(“%**d\n”, FIELD_WIDTH, val);d\n”, FIELD_WIDTH, val);
uses FIELD_WIDTH
240-491 Adv. UNIX:io/9 16
2.3. Precision (.) in printf()2.3. Precision (.) in printf()
SpecifierSpecifier EffectEffect%d%d Min. no. of digits Min. no. of digits
(pad with leading zeros)(pad with leading zeros)
%e, %f%e, %f No. of digits after the decimal pointNo. of digits after the decimal point
%g%g No. of significant digitsNo. of significant digits
%s%s Min. no. of characters from a stringMin. no. of characters from a string
240-491 Adv. UNIX:io/9 17
ExampleExample
int i = 873;int i = 873;float f = 123.94536;float f = 123.94536;char s[] = “Happy Birthday”;char s[] = “Happy Birthday”;printf(“%printf(“%.4d.4d\n%.9d\n”, i, i);\n%.9d\n”, i, i);printf(“%printf(“%.3f.3f\n%\n%.3e.3e\n%\n%.3g.3g\n”, f, f, f);\n”, f, f, f);printf(“%printf(“%.11s.11s\n”, s);\n”, s);
08730873000000873000000873123.945123.9451.293e+021.293e+02124124Happy BirthHappy Birth
240-491 Adv. UNIX:io/9 18
Meaning of *.*Meaning of *.*
Calculate field width Calculate field width andand precision from the precision from the next arguments of the next arguments of the printf()printf()
printf(“%printf(“%*.**.*s\n”, s\n”, field_width, precision, field_width, precision,
str);str);
240-491 Adv. UNIX:io/9 19
2.4. Type Modifiers2.4. Type Modifiers
Place h or l before d, o, x, or uPlace h or l before d, o, x, or u
Place L before e, f, or gPlace L before e, f, or g
LetterLetter EffectEffecthh Specify Specify shortshort typetypell Specify Specify longlong type typeL L Specify Specify long doublelong double type type
240-491 Adv. UNIX:io/9 20
3. Formatted Input: scanf()3. Formatted Input: scanf()
int i, x, y;int i, x, y;float val;float val;char str[100];char str[100];
scanf(“%d”, &i);scanf(“%d”, &i); /* read in integer /* read in integer */*/scanf(“%f”, &val);scanf(“%f”, &val); /* read in float */ /* read in float */scanf(“%s”, str);scanf(“%s”, str); /* read in string /* read in string */*/
scanf(“%d%d”, &x, &y); scanf(“%d%d”, &x, &y); /* read space-separated integers *//* read space-separated integers */
23 2.3hi -5 62
240-491 Adv. UNIX:io/9 21
NotesNotes %d%d will read a sign (e.g. will read a sign (e.g. -27-27))
%f%f will accept a float in fractional or will accept a float in fractional or exponential form (e.g. exponential form (e.g. 2.32.3, , 1.2e+021.2e+02) )
scanf()scanf() will ignore whitespace to get to will ignore whitespace to get to a numbera number– scanf("%d", &x);scanf("%d", &x);
– whitespace includes new lineswhitespace includes new lines
continued
-27
240-491 Adv. UNIX:io/9 22
%s%s only reads non-whitespace characters only reads non-whitespace characters– scanf("%s %s", str1, str2);scanf("%s %s", str1, str2);
– skips whitespace to start of textskips whitespace to start of text– stops reading in text when it gets to a whitespacestops reading in text when it gets to a whitespace– adds ‘\0’adds ‘\0’– the string variable (e.g. the string variable (e.g. str1str1) must have enough memory) must have enough memory
continued
hello andy
240-491 Adv. UNIX:io/9 23
scanf("%d%d", &x, &y);scanf("%d%d", &x, &y);
same assame as scanf(“%d”, &x);scanf(“%d”, &x);scanf(“%d”, &y);scanf(“%d”, &y);
scanf()scanf() will read will read xx and and yy values from the values from the same line, or any distance apart, so long as same line, or any distance apart, so long as the values are separated by whitespace.the values are separated by whitespace.
continued
27 13
240-491 Adv. UNIX:io/9 24
%c%c will read any character (even will read any character (even whitespace):whitespace):scanf(“%c”, &ch);scanf(“%c”, &ch);
Other characters in the Other characters in the scanf()scanf() format format string are used for input matching:string are used for input matching:scanf(“%d-%d %d”, &x, &y, &z);scanf(“%d-%d %d”, &x, &y, &z);
continued
27-13 5
240-491 Adv. UNIX:io/9 25
scanf()scanf() leaves non-matching characters leaves non-matching characters on the input streamon the input stream
scanf("%d", &x);scanf("%d", &x);scanf("%s", str);scanf("%s", str);
scanf()scanf() returnsreturns the number of bound the number of bound variables, or variables, or EOFEOF at end-of-file. at end-of-file.
int num;int num;num = scanf("%d %d", &x, &y);num = scanf("%d %d", &x, &y);
hello
27 13
continued
240-491 Adv. UNIX:io/9 26
scanf()scanf() uses line buffering uses line buffering– when when scanf()scanf() is reading from the keyboard, it is reading from the keyboard, it
only gets a line to process when a only gets a line to process when a RETURNRETURN is is pressedpressed
240-491 Adv. UNIX:io/9 27
3.1. Assignment Supression (*)3.1. Assignment Supression (*)
int month, day, year;int month, day, year;
printf(“Enter date as mm-dd-yy: “);printf(“Enter date as mm-dd-yy: “);scanf(“%dscanf(“%d%*c%*c%d%d%*c%*c%d”, &month, %d”, &month,
&day, &year);&day, &year);printf(“month = %d day = %d year = %d\n”, printf(“month = %d day = %d year = %d\n”,
month, day, year);month, day, year);
Enter date as mm-dd-yy: Enter date as mm-dd-yy: 11-18_9711-18_97month = 11 day = 18 year = 97month = 11 day = 18 year = 97
240-491 Adv. UNIX:io/9 28
3.2. Field Widths3.2. Field Widths
A field width specifies the maximum number of A field width specifies the maximum number of input characters to process (ignoring whitespace input characters to process (ignoring whitespace before the start).before the start).
int x, y;int x, y;scanf(“%scanf(“%2d2d%d”, &x, &y);%d”, &x, &y);printf(“Integers are: %d, %d\n”, x, y);printf(“Integers are: %d, %d\n”, x, y);
123456123456Integers are: 12, 3456Integers are: 12, 3456
240-491 Adv. UNIX:io/9 29
3.3. Scan Sets [...]3.3. Scan Sets [...]
Specify characters that Specify characters that cancan be read. be read.
char z[9];char z[9];printf(“Enter String: “);printf(“Enter String: “);scanf(“scanf(“%[aeiou]%[aeiou]”, z);”, z);printf(“The input was \”%s\”\n”, z);printf(“The input was \”%s\”\n”, z);
Enter String: Enter String: ooeeooahahooeeooahahThe input was “ooeeooa”The input was “ooeeooa”
240-491 Adv. UNIX:io/9 30
Inverted Scan Sets [^...]Inverted Scan Sets [^...]
Specify characters Specify characters notnot to be read. to be read.
char z[9];char z[9];printf(“Enter String: “);printf(“Enter String: “);scanf(“scanf(“%[^aeiou]%[^aeiou]”, z);”, z);printf(“The input was \”%s\”\n”, z);printf(“The input was \”%s\”\n”, z);
Enter String: Enter String: PhreakPhreakThe input was “Phr”The input was “Phr”
240-491 Adv. UNIX:io/9 31
3.4. Handling Incorrect Input3.4. Handling Incorrect Input
Things to remember:Things to remember:
– scanf()scanf() returns when it sees a character returns when it sees a character that it does not want. It leaves the that it does not want. It leaves the character on the input stream;character on the input stream;
– scanf()scanf() returns the number of returns the number of variables it has boundvariables it has bound
continued
240-491 Adv. UNIX:io/9 32
/* Try to read two integers *//* Try to read two integers */#include <stdio.h>#include <stdio.h>
int main()int main(){ int i, j, count;{ int i, j, count; do { do { printf(“Enter two integers: “); printf(“Enter two integers: “); count = scanf(“%d %d, &i, &j)count = scanf(“%d %d, &i, &j);; if (count < 2) { if (count < 2) { /* somthing wrong *//* somthing wrong */ scanf(“ scanf(“%*[^\n]%*[^\n]”);”); /* skip to end of line *//* skip to end of line */ printf(“Incorrect. Try again: “); printf(“Incorrect. Try again: “); } } } while (count < 2); } while (count < 2); /* until valid input *//* until valid input */ : :}}
* supresses assign;[^\n] matches uptonewline (whitespace)
240-491 Adv. UNIX:io/9 33
4. Line I/O4. Line I/O
int puts(char *line);int puts(char *line);
– e.g. e.g. puts(“Hello World”);puts(“Hello World”);
– Adds a newline to its output.Adds a newline to its output.
– If there is an error it returns If there is an error it returns EOFEOF; ; If okay it returns a non-negative integer.If okay it returns a non-negative integer.
240-491 Adv. UNIX:io/9 34
char *gets(char *line);char *gets(char *line);
– e.g: e.g: gets(str);gets(str);
– Reads to a newline in Reads to a newline in stdinstdin; ; replaces newlinereplaces newline by by ‘\0’‘\0’ in input argument in input argument
– gets()gets() returns a returns a NULLNULL when when EOFEOF or an error occurs. or an error occurs.
– Main problemMain problem: : gets()gets() may read in a bigger string may read in a bigger string than can be stored in the variable; than can be stored in the variable; use use fgets()fgets() instead. instead.
Bad style:avoid gets()
240-491 Adv. UNIX:io/9 35
char *fgets(char *line, int n,char *fgets(char *line, int n,FILE *stream);FILE *stream);
– e.g: e.g: fgets(str, 80, stdin);fgets(str, 80, stdin);
– Reads at most Reads at most n-1n-1 chars into chars into lineline, stopping if a newline is , stopping if a newline is encountered;encountered;
– the the newline is includednewline is included in in lineline, and a , and a ‘\0’‘\0’ is added is added
– fgets()fgets() returns a returns a NULLNULL when when EOFEOF or an error occurs. or an error occurs.
240-491 Adv. UNIX:io/9 36
sscanf()sscanf()
int sscanf(char *s, int sscanf(char *s, const char *format, ...);const char *format, ...);
Same as Same as scanf()scanf() but its input comes from but its input comes from the string argument (the string argument (ss) not from ) not from stdinstdin..
Very useful for separatingreading from processingin code.
240-491 Adv. UNIX:io/9 37
Read Read thenthen Process Process
#include <stdio.h>#include <stdio.h>int main()int main(){ char str[120]; /* magic number: poor style! */{ char str[120]; /* magic number: poor style! */ int i, j; int i, j; while (fgets(str,120,stdin) != NULL) { /* read */ while (fgets(str,120,stdin) != NULL) { /* read */
/* process *//* process */ if ( if (sscanf(str, “%d %d”, &i, &j) == 2sscanf(str, “%d %d”, &i, &j) == 2) ) printf(“i = %d j = %d\n”, i, j); printf(“i = %d j = %d\n”, i, j); else if ( else if (sscanf(str, “%d”, &i) == 1sscanf(str, “%d”, &i) == 1)) printf(“i = %d j = ??\n”, i); printf(“i = %d j = ??\n”, i); else else printf(“Could not understand anything!\n”); printf(“Could not understand anything!\n”); : :}}
240-491 Adv. UNIX:io/9 38
5. Character I/O5. Character I/O
int putchar(int c);int putchar(int c);
– e.g.:e.g.: putchar(‘\n’);putchar(‘\n’);
putchar(32);putchar(32);
int getchar(void);int getchar(void);
– e.g.:e.g.: intint ch; ch;ch = getchar();ch = getchar();
while (while (((ch = getchar()ch = getchar())) != EOF) != EOF)......
Remember the brackets.
240-491 Adv. UNIX:io/9 39
CannotCannot “Press any key” “Press any key”
#include <stdio.h>#include <stdio.h>int main()int main(){ char ch; { char ch;
printf(“Press any key to go on...”); printf(“Press any key to go on...”); ch = getchar(); /* type conversion */ ch = getchar(); /* type conversion */ printf(“You pressed ‘%c’\n”, ch); printf(“You pressed ‘%c’\n”, ch); : :}}
ProblemProblem: UNIX line buffering: UNIX line buffering Quick fixQuick fix: say : say “Press RETURN”“Press RETURN”