DPM_C_I/O.doc Page D-1 of 40 Rüdiger Siol :24 - PDF

Contents D C-BASED INPUT/OUTPUT...D-2 D.1 THE C I/O-SYSTEM...D-2 D.2 C I/0 USES STREAMS...D-3 D.2.1 Streams...D-4 D.2.2 Text Streams and Binary Streams...D-5 D.3 UNDERSTANDING PRINTF( ) AND SCANF( )...D-6

Please download to get full document.

View again

of 27
All materials on our website are shared by users. If you have any questions about copyright issues, please report us to resolve them. We are always happy to assist you.

Fan Fiction

Publish on:

Views: 52 | Pages: 27

Extension: PDF | Download: 0

Contents D C-BASED INPUT/OUTPUT...D-2 D.1 THE C I/O-SYSTEM...D-2 D.2 C I/0 USES STREAMS...D-3 D.2.1 Streams...D-4 D.2.2 Text Streams and Binary Streams...D-5 D.3 UNDERSTANDING PRINTF( ) AND SCANF( )...D-6 D.3.1 printf( )...D-6 D Printf Control String and Conversion Specifiers...D-9 D Modifier Tables...D-10 D Flags...D-10 D Conversions...D-11 D Example of printf() usage...d-12 D.3.2 scanf( )...D-13 D Scanf Control String and Conversion Specifiers...D-17 D Length Modifiers And Conversion Specifiers For Formatted Input Functions...D-17 D Length Specifiers...D-17 D Conversion Specifiers...D-18 D Scanset...D-18 D Example of scanf() usage...d-20 D.4 THE C FILE SYSTEM...D-21 D.4.1 fopen( )...D-22 D Example of fopen() usage...d-24 D.4.2 fputc( )...D-25 D Example of fputc() usage...d-25 D.4.3 fgetc( )...D-26 D Example of fgetc() usage...d-26 D.4.4 feof( )...D-27 D Example of feof() usage...d-27 D.4.5 fclose( )...D-28 D Example of fclose() usage...d-28 D.4.6 ferror( ) and rewind( )...D-29 D Example of ferror() usage....d-29 D Example of rewind() usage...d-30 D.4.7 fread( ) and fwrite( )...D-31 D The use of fwrite() and fread()...d-32 D.4.8 fseek( ) and Random-Access I/O...D-33 D Example of fseek() usage...d-34 D.4.9 fprintf( ) and fscanf( )...D-35 D Example of fprintf() usage...d-35 D Example of fscanf() usage...d-36 D.4.10 fflush()...d-37 D Example of fflush() usage...d-38 D.5 ERASING FILES...D-39 D.6 MORE EXAMPLES TO C-BASED I/O...D-40 D.6.1 The use of EOF during keyboard input...d-40 DPM_C_I/O.doc Page D-1 of 40 Rüdiger Siol fwrite Hochschule Fakultät Elektrotechnik und Informatik Information Processing D C-Based Input/Output D.1 The C I/O-System This appendix presents a brief overview of the C I/O system. Even though you will normally use the C++ I/O system, there are several reasons why you may need to understand the fundamentals of C-based I/O. First, if you will be working on C code (especially if you are converting it to C++), then you will need to understand how the C I/O system works. Second, it is common to find both C and C++ I/O within the same program. This is true especially when the program is very large and has been written by multiple programmers over a long period of time. Third, a great number of existing C programs continue to be used and maintained. Finally, many books and periodicals contain programs written in C. To understand these programs, you need to understand the basics of the C l/o system. For C++ programs, you should use the C++ object oriented I/O system. This appendix covers the most commonly used C-based I/O functions. However, the C standard library contains a very rich and diverse assortment of I/O functions-more than can be covered here. If you will be doing extensive work in C, you will want to explore its I/O system in detail. The C-based I/O system requires either the header file stdio.h or the new-style header cstdio . A C program must use the stdio.h since C does not support C++-style headers. A C++ program uses either one. The header cstdio puts its contents into the std namespace. The header file stdio.h puts its contents into the global namespace, which is in keeping with C. The examples in this appendix are C programs, so they use the C-style header stdio.h, and no namespace statement is required. C-Based I/O command line arguments stdin / stdout stderr int main (int argc, char **argv) printf, putchar, puts scanf, getchar, gets Application -program (-software) fprintf, putc, fputs fscanf, getc, fgets fopen, fclose, fgetpos fsetpos, ftell, fseek text file fread sscanf sprintf physical records (r.siol) String Hochschule Ravensburg-Weingarten Technik Wirtschaft Sozialwesen 106 DPM_C_I/O.doc Page D-2 of 40 Rüdiger Siol The C language standard was updated in 1999, resulting in the C99 standard for C. At that time, a few enhancements were made to the C I/O system. However, because C++ is built on C89, it does not support any features added by C99. (Furthermore, at the time of this writing, no widely available compiler supports C99, nor is there any widely distributed code that uses the C99 features.) Thus, none of the features added to the C I/O system by C99 are described here. If you are interested in the C language, including a complete description of its I/O system and those features added by the C99 standard, I recommend my 1 book C: The Complete Reference, 4th edition, McGraw-Hill/Osborne. D.2 C I/0 Uses Streams Like the C++ I/O system, the C-based I/O system operates on streams. At the beginning of a program's execution, three predefined text streams are opened. They are stdin, stdout, and stderr. (Some compilers also open other, implementation-dependent streams.) These streams are the C versions of cin, cout, and cerr, respectively. They each refer to a standard I/O device connected to the system, as shown here: Stream Device stdin keyboard stdout screen stderr screen Remember that most operating systems, including Windows, allow I/O redirection, so functions that read or write to these streams may be redirected to other devices. You should never try to explicitly open or close these streams. Each stream that is associated with a file has a file control structure of type FILE. This structure is defined in stdio.h. You must not make modifications to this file control block. 1 Herbert Schildt DPM_C_I/O.doc Page D-3 of 40 Rüdiger Siol D.2.1 Streams 2 A stream is a logical abstraction that isolates input and output operations from the physical characteristics of terminals and structured storage devices. They provide a mapping between a program s data and the data as actually stored on the external devices. Two forms of mapping are supported, for text streams and for binary streams. Streams also provide buffering, which is an abstraction of a file designed to reduce hardware I/O requests.without buffering, data on an I/O device must be accessed one item at a time. This inefficient I/O processing slows program execution considerably. The stdio.h functions use buffers in primary storage to intercept and collect data as it is written to or read from a file. When a buffer is full its contents are actually written to or read from the file, thereby reducing the number of I/O accesses. A buffer's contents can be sent to the file prematurely by using the fflush() function. The stdio.h header offers three buffering schemes: o unbuffered o block buffered o line buffered. The setvbuf() function is used to change the buffering scheme of any output stream. When an output stream is unbuffered, data sent to it are immediately read from or written to the file. When an output stream is block buffered, data are accumulated in a buffer in primary storage. When full, the buffer's contents are sent to the destination file, the buffer is cleared, and the process is repeated until the stream is closed. Output streams are block buffered by default if the output refers to a file. A line buffered output stream operates similarly to a block buffered output stream. Data are collected in the buffer, but are sent to the file when the line is completed with a newline character ('\n'). A stream is declared using a pointer to a FILE. There are three FILE pointers that are automatically opened for a program: o FILE *stdin o FILE *stdout o FILE *stderr The FILE pointers stdin and stdout are the standard input and output files, respectively, for interactive console I/O. The stderr file pointer is the standard error output file, where error messages are written to. The stderr stream is written to the console. The stdin and stdout streams are line buffered while the stderr stream is unbuffered. 2 Metroworks Corporation; some parts out of the documentation. DPM_C_I/O.doc Page D-4 of 40 Rüdiger Siol D.2.2 Text Streams and Binary Streams In a binary stream, there is no transformation of the characters during input or output and what is recorded on the physical device is identical to the program s internal data representation. A text stream consists of sequences of characters organized into lines, each line terminated by a new-line character. To conform to the host system s convention for representing text on physical devices, characters may have to be added altered or deleted during input and output. Thus, there may not be a one-to-one correspondence between the characters in a stream and those in the external representation. These changes occur automatically as part of the mapping associated with text streams. Of course, the input mapping is the inverse of the output mapping and data that are output and then input through text streams will compare equal with the original data. In MSL 3, the text stream mapping affects only the linefeed (LF) character, \n and the carriage return (CR) character, \r. The semantics of these two control characters are: \n Moves the current print location to the start of the next line. \r Moves the current print location to the start of the current line. where current print location is defined as that location on a display device where the next character output by the fputc function would appear. The ASCII character set defines the value of LF as 0x0a and CR as 0x0d and these are the values that these characters have when they are part of a program's data. On physical devices in the Macintosh operating system, newline characters are represented by 0x0d and CR as 0x0a; in other words, the values are interchanged. To meet this requirement, the MSL C library for the Mac, interchanges these values while writing a file and again while reading so that a text stream will be unchanged by writing to a file and then reading back. MPW chose 0x0a for the newline character in its text file, so, when the MPW switch is on, this interchange of values does not take place. However, if you use this option, you must use the MSL C and C++ libraries that were compiled with this option on. These versions of the libraries are marked with an N (on 68k) or NL (on PPC), for example ANSI (N/2i) C.68k.Lib or ANSI (NL) C.PPC.Lib. See the notes on the mpwc_newline pragma in the CodeWarrior C Compilers Reference. On Windows, the situation is different. There, lines are terminated with the character pair CR/LF. As a consequence, in the Windows implementation of MSL, when a text stream is written to a file, a single newline character is converted to the character pair CR/LF and the reverse transformation is made during reading. The library routines that read a file have no means of determining the mode in which text files were written and thus some assumptions have to be made. On the Mac, it is assumed that the Mac convention is used. Under MPW, it is assumed that the MPW convention is to be used and on Windows, the DOS convention. 3 MSL Metroworks Standard Library DPM_C_I/O.doc Page D-5 of 40 Rüdiger Siol D.3 Understanding printf( ) and scanf( ) The two most commonly used C-based I/O functions are printf() and scanf(). The printf( ) function writes data to the console; scanf( ), its complement, reads data from the keyboard. Because the C language does not support operator overloading, or the use of and as I/O operators, it relies on printf( ) and scanf( ) for console I/O. Both printf( ) and scanf( ) can operate on any of the built-in data types, including characters, strings, and numbers. However, since these functions are not object-oriented, they cannot operate directly upon class types that you create. D.3.1 printf( ) The printf( ) function has this prototype: int printf(const char *fmt_string,... ); The first argument, fmt_string, defines the way any subsequent arguments are displayed. This argument is often called the format string. It contains two things: text and format specifiers. Text is printed on the screen and has no other effect. The format specifiers define the way arguments that follow the format string are displayed. A format specifier begins with a percent sign, and is followed by the format code. The format specifiers are shown in Format Table. There must be exactly the same number of arguments as there are format specifiers, and the format specifiers and the arguments are matched in order. Text and format specifiers in printf The printf() function has the prototype: int printf (const char * format, ); %[Flag][Width][.Precision][Length modifier]conversion Specifier %[F][W][P][L]C % = A percent sign F = [Flag] -, +, 0, # or space W = [Width] decimal digit string P = [Precision]. or.* or. decimal digit string L = [Length modifier] h, l, hh, ll, j, z or t C = Conversion Specifier c,d,e,e,f,f,g,g,i,n,o,p,s,u,x,x or % Options are shown in []. (r.siol) Hochschule Ravensburg-Weingarten Technik Wirtschaft Sozialwesen 111 For example, this printf( ) call, printf( hi %c %d %s , 'c', 10, there! ); displays: Hi c 10 there!. The printf( ) function returns the number of characters output. It returns a negative value if an error occurs. DPM_C_I/O.doc Page D-6 of 40 Rüdiger Siol The format specifiers The format specifiers may have modifiers that specify the field width, the number of decimal places, and a left-justification flag. An integer placed between the % sign and the format specifier acts as a minimum-field-width specifier. Code Format %c Character %d Signed decimal integers %i Signed decimal integers %e Scientific notation (lowercase e) %E Scientific notation (uppercase E) %f Decimal floating point %g Uses %e or %f, whichever is shorter %G Uses %E or %F, whichever is shorter %o Unsigned octal %s String of characters %u Unsigned decimal integers %x Unsigned hexadecimal (lowercase letters) %X Unsigned hexadecimal (uppercase letters) %p Displays a pointer %n The associated argument is a pointer to an integer into which the number of characters written so far is placed %% Displays a % sign This pads the output with spaces to ensure that it is at least a certain minimum length. If the string or number is greater than that minimum, it will be printed in full, even if it overruns the minimum. If you want to pad with 0s, place a 0 before the field-width specifier. For example, %05d will pad a number of less than five digits with 0s so that its total length is five. To specify the number of decimal places printed for a floating-point number, place a decimal point after the field-width specifier, followed by the number of decimal places you want to display. For example, %10.4f will display a number at least ten characters wide, with four decimal places. When this is applied to strings or integers, the number following the period specifies the maximum field length. Far example, %5.7s will display a string that is at least five characters long, but that does not exceed seven characters. lf the string is longer than the maximum field width, the characters will be truncated from the end. By default, all output is right-justified: If the field width is larger than the data printed, the data will be placed on the right edge of the field. You can force the information to be leftjustified by placing a minus sign directly after the %. For example, %-10.2f will left-justify a floating-point number, with two decimal places in a ten-character field. DPM_C_I/O.doc Page D-7 of 40 Rüdiger Siol Here is a program that demonstrates field-width specifiers and left-justification: int main() printf( %10.5f \n , ); printf( %-10.5f \n , ); printf( %10.5s \n , Hello there ); printf( %-10.5s \n , Hello there ); return 0; This program displays the following output: Hello Hello There are two format specifier modifiers that allow printf( ) to display short and long integers. These modifiers can be applied to the d, i, o, u and x type specifiers. The l (ell) modifier tells printf( ) that a long data type follows. For example, %ld means that a long int is to be displayed. The h modifier instructs printf( ) to display a short int. Therefore, %hu indicates that the data is of the short, unsigned integer type. The l and h modifiers can also be applied to the n specifier, to indicate that the corresponding argument is a pointer to a long or short integer, respectively. If your compiler fully complies with Standard C++, then you can use the l modifier with the c format to indicate a wide character. You can also use the l modifier with the s format to indicate a wide-character string. The L modifier can prefix the floating-point specifiers e, f and g. In this context, it indicates that a long double follows. DPM_C_I/O.doc Page D-8 of 40 Rüdiger Siol D Printf Control String and Conversion Specifiers The format character array contains normal text and conversion specifications. Conversion specifications must have matching arguments in the same order in which they occur in format. The various elements of the format string is specified in the ANSI standards to be in this order from left to right. o Apercent sign o Optional flags -,+,0,# or space o Optional minimum field width specification o Optional precision specification o Optional size specification o Conversion specifier c,d,e,e,f,f,g,g,i,n,o,p,s,u,x,x or % A conversion specification describes the format its associated argument is to be converted to. A specification starts with a percent sign (%), optional flag characters, an optional minimum width, an optional precision width, and the necessary, terminating conversion type. Doubling the percent sign (%%) results in the output of a single %. An optional flag character modifies the formatting of the output; it can be left or right justified, and numerical values can be padded with zeroes or output in alternate forms. More than one optional flag character can be used in a conversion specification. Length Modifiers And Conversion Specifiers For Formatted Output Functions see following tables, describes the flag characters. The optional minimum width is a decimal digit string. If the converted value has more characters that the minimum width, it is expanded as required. If the converted value has fewer characters than the minimum width, it is, by default, right justified (padded on the left). If the - flag character is used, the converted value is left justified (padded on the right). NOTE The maximum minimum field width allowed in MSL Standard Libraries is 509 characters. The optional precision width is a period character (.) followed by decimal digit string. For floating point values, the precision width specifies the number of digits to print after the decimal point. For integer values, the precision width functions identically to, and cancels, the minimum width specification. When used with a character array, the precision width indicates the maximum width of the output. A minimum width and a precision width can also be specified with an asterisk (*) instead of a decimal digit string. An asterisk indicates that there is a matching argument, preceding the conversion argument, specifying the minimum width or precision width. The terminating character, the conversion type, specifies the conversion applied to the conversion specification's matching argument Length Modifiers And Conversion Specifiers For Formatted Output Functions see following tables, describes the conversion type characters. DPM_C_I/O.doc Page D-9 of 40 Rüdiger Siol D Modifier Tables Length Modifiers And Conversion Specifiers For Formatted Output Functions Modifier Description Size h The h flag followed by d, i, o, u, x, or X conversion specifier indicates that the corresponding argument is a short int or unsigned short int. l The lower case L followed by d, i, o, u, x, or X conversion specifier indicates the argument is a long int or unsigned long int. The lower case L followed by a c conversion specifier, indicates that the argument is of type wint_t. The lower case L followed by an s conversion specifier, indicates that the argument is of type wchar_t. ll The double l followed by d, i, o, u, x, or X conversion specifier indicates the argument is a long long or unsigned long long L The upper case L followed by e, E, f, g, or G conversion specifier indicates a long do
Related Search
Similar documents
View more...
We Need Your Support
Thank you for visiting our website and your interest in our free products and services. We are nonprofit website to share and download documents. To the running of this website, we need your help to support us.

Thanks to everyone for your continued support.

No, Thanks