today
DESCRIPTION
Today. Schedule Pong due Friday (April 11) Homework #9 due Friday (April 11) Homework #10 (on-line) Pointer Quizzes Student Evaluations Pong Questions?? I/O. 3.4 – I/O. Required : PM: Ch 11, pgs 205-243 Recommended : K&R, Chapter 7 Data Input and Output. “Gripe Sheet…”. - PowerPoint PPT PresentationTRANSCRIPT
S09: I/O
Required: PM: Ch 11, pgs 205-243
Recommended: K&R, Chapter 7Data Input and Output
BYU CS 224 Input and Output 2
CS 224Chapter Project Homework
S00: IntroductionUnit 1: Digital Logic
S01: Data TypesS02: Digital Logic
L01: Warm-upL02: FSM
HW01HW02
Unit 2: ISAS03: ISAS04: MicroarchitectureS05: Stacks / InterruptsS06: Assembly
L03: BlinkyL04: MicroarchL05b: Traffic LightL06a: Morse Code
HW03HW04HW05HW06
Unit 3: CS07: C LanguageS08: PointersS09: StructsS10: I/O
L07b: Morse IIL08a: LifeL09b: Snake
HW07HW08HW09HW10
Input and Output 3BYU CS 224
Learning Outcomes… Students will be able to:
Find and use standard C functions.
Interpret a data stream according to a specified format.
Direct character output to a data stream.
Assign a data stream to an I/O device, file, or memory.
Input and Output 4BYU CS 224
Topics… Standard Libraries Input/Output Data Streams printf() scanf() File I/O fprintf and fscanf sprintf and sscanf
Quiz 10.1
BYU CS 224 Input and Output 5
2. Name 5 ways to improve your skills as a programmer
1. What makes one person’s code better/worse than another?
Input and Output 6BYU CS 224
C Standard Library Standard libraries promote cross-platform
compatibility. Useful for building complex programs. Functions, types, and macros of the standard
library are accessed by the #include directive. Headers may be included in any order (and any
number of times). Actual I/O libraries can be linked statically or
dynamically.
Standard Libraries
Input and Output 7BYU CS 224
ANSI Standard Libraries <assert.h> Diagnostics <ctype.h> Character Class Tests <errno.h> Error Codes Reported by (Some) Library
Functions <float.h> Implementation-defined Floating-Point Limits <limits.h> Implementation-defined Limits <locale.h> Locale-specific Information <math.h> Mathematical Functions <setjmp.h> Non-local Jumps <signal.h> Signals <stdarg.h> Variable Argument Lists <stddef.h> Definitions of General Use <stdio.h> Input and Output <stdlib.h> Utility functions <string.h> String functions <time.h> Time and Date functions
Standard Libraries
Input and Output 8BYU CS 224
<string.h> Copy one string into another
char* strcpy (const char* dest, const char* src); char* strncpy (const char* string1, const char* string2, size_t n)
Compare string1 and string2 to determine alphabetic order int strcmp (const char* string1,const char* string2); int strncmp (const char* string1, char* string2, size_t n);
Determine the length of a string int strlen (const char* string);
Append characters from string2 to string1 char* strcat (const char* string1, const char* string2); char* strncat (const char* string1, const char* string2, size_t n);
Find a string in a string char* strstr (char* string1, const char* string2);
String Library
Input and Output 9
<string.h> memchr memcmp memcpy memmove memset
strchr strcoll strcspn strerror strpbrk strrchr strspn strtok strxfrm
BYU CS 224
String Library
Input and Output 10
<stdlib.h> String conversion
atof Convert string to double atoi Convert string to integer atol Convert string to long integer atoll Convert string to long long integer strtod Convert string to double strtof Convert string to float strtol Convert string to long integer strtold Convert string to long double strtoll Convert string to long long integer strtoul Convert string to unsigned long integer strtoullConvert string to unsigned long long integer
BYU CS 224
Standard General Utilities Library
Input and Output 11
<stdlib.h> Pseudo-random sequence generation
rand Generate random number srand Initialize random number generator
Dynamic memory management calloc Allocate and zero-initialize array free Deallocate memory block malloc Allocate memory block realloc Reallocate memory block
Searching and sorting bsearch Binary search in array qsort Sort elements of array
BYU CS 224
Standard General Utilities Library
Input and Output 12
<stdlib.h> Integer arithmethics
abs Absolute value div Integral division labs Absolute value ldiv Integral division llabs Absolute value lldiv Integral division
Types div_t Structure returned by div (type ) ldiv_t Structure returned by ldiv (type ) lldiv_t Structure returned by lldiv (type ) size_t Unsigned integral type (type )
BYU CS 224
Standard General Utilities Library
Input and Output 13
Quiz 10.2
1. In which standard library would I find the following?
a) absb) malloc / freec) memcpy / memsetd) printf / putchar
2. What is an I/O Stream?
BYU CS 224
Input and Output 14BYU CS 224
I/O Data Streams I/O is not directly supported by C but by a set of standard
library functions defined by the ANSI C standard. The stdio.h header file contains function declarations for I/O and
preprocessor macros related to I/O. stdio.h does not contain the source code for I/O library functions!
All C character based I/O is performed on streams. All I/O streams must be opened and closed A sequence of characters received from the keyboard is an
example of a text stream In standard C there are 3 streams automatically opened
upon program execution: stdin is the input stream stdout is the output stream stderr stream for error messages
Data Streams
Input and Output 15BYU CS 224
Formatted Output The printf function outputs formatted values to
the stdout stream using putcprintf( const char *format, ... );
The format string contains two object types: Ordinary characters that are copied to the output
stream Conversion specifications which cause conversion
and printing of the next argument in the argument list.printf("\nX = %d, Y = %d", x, y);
printf()
Conversionspecifications Characters
Input and Output 16BYU CS 224
Format Options The format specifier uses the format:
%[flags][width][.precision][length]specifier Formatting options are inserted between the %
and the conversion character: Field width "%4d" Length modifier "%ld" Left justified "%-4d" Zero padded "%04d" Sign "%+4d" Variable field width "%*d" Characters "\a", "\b", "\n", "\r", "\t", "\v", "\xnn"
printf()
Specifiers:Decimal %d or %iString %sCharacter %cHexadecimal %xUnsigned decimal %uFloating point %fScientific notation %eHex floating point %aPointer %p% %%
Input and Output 17BYU CS 224
Formatted Output A period separates the field width from the precision
when formatting floating point numbers:printf("Speed = %10.2f", speed);
A variable field width is specified using an asterisk (*) formatting option along with a length argument (which must be an int):
printf("%*s", max, s); Left justification is specified by a minus
character (-). The plus character (+) isreplaced by the sign (either “+” or “-”). A space (' ') is replace by “-” if negative.
printf("%-+04d", 10);
printf()
\a bell (alert)
\n newline
\r return
\t tab
\b backspace
\\ backslash
\' single quote
\" double quote
\0nnn ASCII code – oct
\xnnn ASCII code – hex
Input and Output 18BYU CS 224
Formatted Output Examples
int a = 100;int b = 65;char c = 'z';char banner[ ] = "Hola!";double pi = 3.14159;
printf("The variable 'a' decimal: %d\n", a);printf("The variable 'a' hex: %x\n", a);printf("'a' plus 'b' as character: %c\n", a+b);printf("A char %c.\t A string %s\n A float %7.4f\n", c, banner, pi);
printf()
Decimal %d or %iString %sCharacter %cHexadecimal %xUnsigned decimal %uFloating point %fScientific notation %ePointer %p% %%
Input and Output 19BYU CS 224
Full Formatted Output Enableprintf()
Input and Output 20BYU CS 224
Formatted Input The function scanf is similar to printf, providing
many of the same conversion facilities in the opposite direction:
scanf( const char *format, ... ); reads characters from the standard input (stdin), interprets them according to the specification in format, stores the results through the remaining arguments.
The format argument is a string; all other arguments must be a pointers indicating where the corresponding converted input should be stored.
scanf()
Input and Output 21BYU CS 224
scanf Conversion For each data conversion, scanf will skip whitespace
characters and then read ASCII characters until it encounters the first character that should NOT be included in the converted value.
%d Reads until first non-digit.%x Reads until first non-digit (in hex).%s Reads until first whitespace character.
Literals in format string must match literals in theinput stream.
Data arguments must be pointers, because scanfstores the converted value to that memory address.
scanf()
Input and Output 22BYU CS 224
scanf Return Value The scanf function returns an integer, which indicates
the number of successful conversions performed. This lets the program check whether the input stream
was in the proper format. Example:
scanf("%s %d/%d/%d %lf", name, &bMonth, &bDay, &bYear, &gpa);
Input Stream Return ValueMudd 02/16/69 3.02 5
Muss 02 16 69 3.02 2
Doesn't match literal '/', so scanf quitsafter second conversion.
scanf()
Input and Output 23BYU CS 224
Quiz 10.3 What will the following do?
1. Output of the programto the right?
2. int n = 0;scanf("%d", n);
3. scanf("%d");
4. printf("\nValue=%d");
#include <stdio.h>
int main(void){ const char text[] = "Hello world"; int i; for ( i = 1; i < 12; ++i ) { printf("\"%*s\"\n", i, text); }}
Input and Output 24BYU CS 224
I/O from Files General-purpose I/O functions allow us to specify the
stream on which they act Must declare a pointer to a FILE struct for each
physical file we want to manipulateFILE* infile;FILE* outfile;
The I/O stream is "opened" and the FILE struct instantiated by the fopen function
Arguments include the name of file to open and a description of the operation modes we want to perform on that file
infile = fopen("myinfile", "r");outfile = fopen("myoutfile", "w");
Returns pointer to file descriptor or NULL if unsuccessful
File I/O
Input and Output 25BYU CS 224
I/O from Files File operation modes are:
"r" for reading "w" for writing (an existing file will lose its contents) "a" for appending "r+" for reading and writing "b" for binary data
Once a file is opened, it can be read from or written to with functions such as
fgetc Read character from stream fputc Write character to stream fread Read block of data from stream fwrite Write block of data to stream fseek Reposition stream position indicator fscanf Read formatted data from stream fprintf Write formatted output to stream
File I/O
Input and Output 26BYU CS 224
I/O from Files#define LIMIT 1000int main(){ FILE* infile; FILE* outfile; double prices[LIMIT]; int i=0;
infile = fopen("myinputfile", "r"); // open for reading outfile = fopen("myoutputfile", "w"); // open for writting if ((infile != NULL) && (outfile != NULL)) { while (i < LIMIT) { if ((fscanf(infile, "%lf", &prices[i]) == EOF)) break; printf("\nprice[%d] = %10.2lf", i, prices[i]); // ... process prices[i] i += 1; } } else printf("\nfopen unsuccessful!"); fclose(infile); fclose(outfile);}
File I/O
Input and Output 27BYU CS 224
Quiz 10.4 Write an ASCII to integer function (ascii to integer).
1. Account for leading spaces and negative numbers.2. Stop conversion at any non-digit.3. Use a ternary operator somewhere in your implementation
Prototype:int my_atoi(char* s);
Exampleprintf("-345 = %d", my_atoi(" -345"));
Input and Output 28BYU CS 224
sprintf and sscanf sprintf converts binary numbers to a string
int sprintf(char* buffer, const char* fmt,…); buffer – char array big enough to hold converted number(s) fmt – format specification Variable list to be converted Returns number of characters in converted string (not including null
character Useful in converting data to strings
sscanf converts a string to binary numbers int sscanf(char* buffer, const char* fmt,…);
buffer – char array contains data to be converted fmt – format specification List of pointers to variables to hold converted values Returns number of items converted
Useful to convert character data files
sprintf / sscanf
Input and Output 29BYU CS 224