Presentation is loading. Please wait.

Presentation is loading. Please wait.

S09: I/O Required: PM: Ch 11, pgs 205-243 Recommended: K&R, Chapter 7 Data Input and Output.

Similar presentations


Presentation on theme: "S09: I/O Required: PM: Ch 11, pgs 205-243 Recommended: K&R, Chapter 7 Data Input and Output."— Presentation transcript:

1 S09: I/O Required: PM: Ch 11, pgs Recommended: K&R, Chapter 7 Data Input and Output

2 BYU CS 224Input and Output2 CS 224 ChapterProjectHomework S00: Introduction Unit 1: Digital Logic S01: Data Types S02: Digital Logic L01: Warm-up L02: FSM HW01 HW02 Unit 2: ISA S03: ISA S04: Microarchitecture S05: Stacks / Interrupts S06: Assembly L03: Blinky L04: Microarch L05b: Traffic Light L06a: Morse Code HW03 HW04 HW05 HW06 Unit 3: C S07: C Language S08: Pointers S09: Structs S10: I/O L07b: Morse II L08a: Life L09b: Snake HW07 HW08 HW09 HW10

3 BYU CS 224Input and Output3 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.

4 BYU CS 224Input and Output4 Topics… Standard Libraries Input/Output Data Streams printf() scanf() File I/O fprintf and fscanf sprintf and sscanf

5 Quiz 10.1 BYU CS 224Input and Output5 2.Name 5 ways to improve your skills as a programmer 1.What makes one person’s code better/worse than another?

6 BYU CS 224Input and Output6 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

7 BYU CS 224Input and Output7 ANSI Standard Libraries Diagnostics Character Class Tests Error Codes Reported by (Some) Library Functions Implementation-defined Floating-Point Limits Implementation-defined Limits Locale-specific Information Mathematical Functions Non-local Jumps Signals Variable Argument Lists Definitions of General Use Input and Output Utility functions String functions Time and Date functions Standard Libraries

8 BYU CS 224Input and Output8 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

9 memchr memcmp memcpy memmove memset strchr strcoll strcspn strerror strpbrk strrchr strspn strtok strxfrm BYU CS 224Input and Output9 String Library

10 String conversion atofConvert string to double atoiConvert string to integer atolConvert string to long integer atollConvert string to long long integer strtodConvert string to double strtofConvert string to float strtolConvert string to long integer strtoldConvert string to long double strtollConvert string to long long integer strtoulConvert string to unsigned long integer strtoullConvert string to unsigned long long integer BYU CS 224Input and Output10 Standard General Utilities Library

11 Pseudo-random sequence generation randGenerate random number srandInitialize random number generator Dynamic memory management callocAllocate and zero-initialize array freeDeallocate memory block mallocAllocate memory block reallocReallocate memory block Searching and sorting bsearchBinary search in array qsortSort elements of array BYU CS 224Input and Output11 Standard General Utilities Library

12 Integer arithmethics absAbsolute value divIntegral division labsAbsolute value ldivIntegral division llabsAbsolute value lldivIntegral division Types div_tStructure returned by div (type ) ldiv_tStructure returned by ldiv (type ) lldiv_tStructure returned by lldiv (type ) size_tUnsigned integral type (type ) BYU CS 224Input and Output12 Standard General Utilities Library

13 Quiz In which standard library would I find the following? a)abs b)malloc / free c)memcpy / memset d)printf / putchar 2.What is an I/O Stream? BYU CS 224Input and Output13

14 BYU CS 224Input and Output14 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

15 BYU CS 224Input and Output15 Formatted Output The printf function outputs formatted values to the stdout stream using putc printf( 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() Conversion specifications Characters

16 BYU CS 224Input and Output16 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 %i String %s Character %c Hexadecimal %x Unsigned decimal %u Floating point %f Scientific notation %e Hex floating point %a Pointer %p % %

17 BYU CS 224Input and Output17 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 (+) is replaced by the sign (either “+” or “-”). A space (' ') is replace by “-” if negative. printf("%-+04d", 10); printf() \abell (alert) \nnewline \rreturn \ttab \bbackspace \\backslash \'\'single quote \"\"double quote \0nnnASCII code – oct \xnnnASCII code – hex

18 BYU CS 224Input and Output18 Formatted Output Examples int a = 100; int b = 65; char c = 'z'; char banner[ ] = "Hola!"; double pi = ; 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 %i String %s Character %c Hexadecimal %x Unsigned decimal %u Floating point %f Scientific notation %e Pointer %p % %

19 BYU CS 224Input and Output19 Full Formatted Output Enable printf()

20 BYU CS 224Input and Output20 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()

21 BYU CS 224Input and Output21 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 the input stream. Data arguments must be pointers, because scanf stores the converted value to that memory address. scanf()

22 BYU CS 224Input and Output22 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 StreamReturn Value Mudd 02/16/ Muss Doesn't match literal '/', so scanf quits after second conversion. scanf()

23 BYU CS 224Input and Output23 Quiz 10.3 What will the following do? 1.Output of the program to the right? 2.int n = 0; scanf("%d", n); 3. scanf("%d"); 4.printf("\nValue=%d"); #include int main(void) { const char text[] = "Hello world"; int i; for ( i = 1; i < 12; ++i ) { printf("\"%*s\"\n", i, text); }

24 BYU CS 224Input and Output24 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 manipulate FILE* 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

25 BYU CS 224Input and Output25 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

26 BYU CS 224Input and Output26 I/O from Files #define LIMIT 1000 int 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

27 BYU CS 224Input and Output27 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); Example printf("-345 = %d", my_atoi(" -345"));

28 BYU CS 224Input and Output28 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

29 BYU CS 224Input and Output29


Download ppt "S09: I/O Required: PM: Ch 11, pgs 205-243 Recommended: K&R, Chapter 7 Data Input and Output."

Similar presentations


Ads by Google