programming in c

23
Programming in C Input / Output Input / Output

Upload: william-walls

Post on 30-Dec-2015

38 views

Category:

Documents


1 download

DESCRIPTION

Programming in C. Input / Output. stdin, stdout, stderr. When your C program begins to execute, three input/output devices are opened automatically. stdin The “standard input” device, usually your keyboard stdout The “standard output” device, usually your monitor stderr - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Programming in C

Programming in C

Input / OutputInput / Output

Page 2: Programming in C

7/28/09

stdin, stdout, stderr

• When your C program begins to execute, three When your C program begins to execute, three input/output devices are opened automatically.input/output devices are opened automatically.

• stdinstdin– The “standard input” device, usually your keyboard

• stdoutstdout– The “standard output” device, usually your monitor

• stderrstderr– The “standard error” device, usually your monitor

• Some C library I/O functions automatically use Some C library I/O functions automatically use these devicesthese devices

Page 3: Programming in C

7/28/09

Formatted Console Output

• In C, formatted output is created using the In C, formatted output is created using the printf( ) function. function.

• printf( ) outputs text to outputs text to stdout• The basic function call to The basic function call to printf( ) is of the is of the

formform printf( format, arg1, arg2, … );

where the format is a string containingwhere the format is a string containing– conversion specifications– literals to be printed

Page 4: Programming in C

7/28/09

printf( ) conversionsConversions specifications begin with Conversions specifications begin with %% and end and end

with a conversion character.with a conversion character.

Between the Between the %% and the conversion character MAY and the conversion character MAY be, in orderbe, in order• A minus sign specifying left-justification• The minimum field width• A period separating the field width and precision• The precision that specifies

• Maximum characters for a string• Number of digits after the decimal for a floating point• Minimum number of digits for an integer

• An h for “short” or an l (letter ell) for long

See K&R section 7.2 and appendix section B1.2See K&R section 7.2 and appendix section B1.2

Page 5: Programming in C

7/28/09

Common printf( ) Conversions• %d -- the int argument is printed as a decimal number -- the int argument is printed as a decimal number• %u -- the int argument is printed as an unsigned number -- the int argument is printed as an unsigned number• %s -- prints characters from the string until ‘\0’ is seen -- prints characters from the string until ‘\0’ is seen

or the number of characters in the (optional) precision or the number of characters in the (optional) precision have been printed (more on this later)have been printed (more on this later)

• %f -- the double argument is printed as a floating point -- the double argument is printed as a floating point numbernumber

• %x, , %X -- the int argument is printed as a hexadecimal -- the int argument is printed as a hexadecimal number (without the usual leading “0x”)number (without the usual leading “0x”)

• %c - the int argument is printed as a single character - the int argument is printed as a single character• %p - the pointer argument is printed (implementation - the pointer argument is printed (implementation

dependent)dependent)

Page 6: Programming in C

7/28/09

printf( ) Examplesint anInt = 5678;double aDouble = 4.123;#define NAME “Bob”

/* what is the output from each printf( ) */printf (“%d is a large number\n”, anInt);printf (“%8d is a large number\n”, anInt);printf (“%-8d is a large number\n”, anInt);printf (“%10.2f is a double\n”, aDouble);printf( “The sum of %d and %8.4f is %12.2f\n”,

anInt, aDouble, anInt + aDouble);printf (“Hello %s\n”, NAME);

Page 7: Programming in C

7/28/09

Formatted Output Example

• Use field widths to align output in columnsUse field widths to align output in columnsint i;for (i = 1 ; i < 5; i++) printf("%2d %10.6f %20.15f\n", i,sqrt(i),sqrt(i));

12 1234567890 1234567890123456789012 1234567890 12345678901234567890 1 1.000000 1.000000000000000 2 1.414214 1.414213562373095 3 1.732051 1.732050807568877 4 2.000000 2.000000000000000

Page 8: Programming in C

7/28/09

Keyboard Input

In C, keyboard input is accomplished using the In C, keyboard input is accomplished using the scanf( )( ) function. function. scanf reads user input from reads user input from stdin.

Calling Calling scanf( ) is similar to calling is similar to calling printf( )scanf( format, arg1, arg2, ... )

The format string has a similar structure to the format string in The format string has a similar structure to the format string in printf( ). The arguments are the The arguments are the addresses of the of the variables into which the input is store.variables into which the input is store.

See K & R section 7.4 and Appendix section B1.3 for a detailed See K & R section 7.4 and Appendix section B1.3 for a detailed description of description of scanf( )

Page 9: Programming in C

7/28/09

scanf( ) format stringThe The scanf( ) format string usually contains format string usually contains

conversion specifications that tell conversion specifications that tell scanf( ) how how to interpret the next “to interpret the next “input field”. An input field ”. An input field is a string of non-whitespace characters.is a string of non-whitespace characters.

The format string usually containsThe format string usually contains– Blanks or tabs which are ignored– Ordinary characters which are expected to match the

next (non-whitespace) character input by the user– Conversion specifications usually consisting

• % character indicating the beginning of the conversion• An optional h, l (ell) or L• A conversion character which indicates how the input field

is to be interpreted.

Page 10: Programming in C

7/28/09

Common scanf( ) conversions• %d -- a decimal (integer) number -- a decimal (integer) number• %u - an unsigned decimal (integer) number - an unsigned decimal (integer) number• %x -- a hexadecimal number -- a hexadecimal number

– The matching argument is the address of an int– May be preceded by h to indicate that the argument is the address of a short or

by l (ell) to indicate that the argument is the address of a long rather than an int

• %f, %e -- a floating point number with optional sign, optional decimal -- a floating point number with optional sign, optional decimal point, and optional exponentpoint, and optional exponent– The matching argument is the address of a float– May be preceded by l (ell) to indicate the argument is of the address of a

double rather than a float• %s -- a word (a string delimited by white space, not an entire line) -- a word (a string delimited by white space, not an entire line)

– The matching argument is the address of a char or the name of a char array– The caller must insure the array is large enough to for the input string and the

terminating \0 character– More on this later

• %c - a single character - a single character– The matching arguments is the address of a char– Does not skip over white-space– More on this later

Page 11: Programming in C

7/28/09

scanf( ) examplesint age;double gpa;char initial;

printf(“ input your middle initial: “);scanf (“%c”, &initial ); // note &printf(“Input your age: “);scanf( “%d”, &age );printf(“ input your gpa: “);scanf (“%lf”, &gpa );

Page 12: Programming in C

7/28/09

Unix input redirection• By default, By default, stdin is associated with the user’s keyboard, is associated with the user’s keyboard,

but Unix allows us to redirect but Unix allows us to redirect stdin to read data from a file to read data from a file when your program is executed. All when your program is executed. All scanf( ) statements statements in your program read from this file instead of the user’s in your program read from this file instead of the user’s keyboard with no change to your code.keyboard with no change to your code.

• Redirecting input from a file is useful for debugging -- you Redirecting input from a file is useful for debugging -- you don’t have to continually retype your input.don’t have to continually retype your input.

• Suppose your program’s name is Suppose your program’s name is Project1 and you wish and you wish to get your input from a file named to get your input from a file named data1. To redirect . To redirect stdin to read from to read from data1data1, use this command at the Unix , use this command at the Unix promptprompt

unix> Project1 < data1

Page 13: Programming in C

7/28/09

Unix output redirection

• By default, By default, stdout is associated with the user’s console, is associated with the user’s console, but Unix allows us to redirect but Unix allows us to redirect stdout to output text to a file to output text to a file when your program is executed. All when your program is executed. All printf( ) statements statements in your program output to this file instead of the user’s in your program output to this file instead of the user’s console, otherwise your program is unaffected.console, otherwise your program is unaffected.

• Suppose your program’s name is Suppose your program’s name is Project1 and you wish and you wish to write your output to a file named to write your output to a file named llogfile1. To redirect . To redirect sstdout to write to to write to llogfile1, use this command at the Unix , use this command at the Unix promptprompt

unix> Project1 > logfile

• Can you redirect both input and output?Can you redirect both input and output?

Page 14: Programming in C

7/28/09

Text File I/O• Reading and writing from/to a text file is similar to getting Reading and writing from/to a text file is similar to getting

input from input from stdin (with (with scanf) and writing to ) and writing to stdout (with (with printf).).

• Reading data from a text file is accomplished with the Reading data from a text file is accomplished with the function function fscanf( ). This function works the same as This function works the same as scanf( ), but requires an additional parameter which is a but requires an additional parameter which is a “handle” to the file.“handle” to the file.

• Reading a line from a text file is accomplished using the Reading a line from a text file is accomplished using the fgets( ) function. This function is similar to function. This function is similar to gets( ) but but requires a “handle” to a file and a max character count.requires a “handle” to a file and a max character count.

• Similarly, writing to a text file is accomplished with the Similarly, writing to a text file is accomplished with the function function fprintf() which works the same as which works the same as printf( ), but also requires a “handle” to the file to be read.but also requires a “handle” to the file to be read.

Page 15: Programming in C

7/28/09

Opening and ClosingTo read or write from a text file using To read or write from a text file using fscanf( ), fegets( ) or or fprintf( ), the file must first be the file must first be opened using opened using fopen( ). The file should be The file should be closed using closed using fclose( ) when all I/O is complete. when all I/O is complete.

fopen( ) returns a handle to the file as the type returns a handle to the file as the type FILE* (a pointer to a FILE struct) which is then (a pointer to a FILE struct) which is then used as the argument to used as the argument to fscanf(), fgets( ), fprintf( ) and and fclose( ).

The return value from The return value from fopen( ) should be checked should be checked to insure that the file was in fact opened.to insure that the file was in fact opened.

Page 16: Programming in C

1/22/10

fopen( )• fopen( ) requires two parameters requires two parameters

– The name of the text file to be opened– The text file open “mode”

• “r” - open the file for reading only

• “w” - create the file for writing; if the file exists, discard the its contents

• “a” - append; open or create the file for writing at the end

• “r+” - open the file for reading and writing

• “w+” - create the file for reading and writing; if the file exists, discard its contents

• “a+” - open or create the file for reading or writing at the end

• See K & R appendix B1.1See K & R appendix B1.1

Page 17: Programming in C

1/22/10

Using fopen( )

• Open the file named “Open the file named “bob.txt” for reading” for reading

FILE * myFile = fopen( “bob.txt”, “r”);• If If fopen( ) fails, the special value fails, the special value NULL is is

returned. All calls to returned. All calls to fopen should be checked should be checked

FILE *myFIle = fopen (“bob.txt”, “r”)

If (myFile == NULL)

{

/* handle the error */

}

Page 18: Programming in C

7/28/09

fscanf.c#include <stdio.h>#include <stdlib.h> /* for “exit” */int main ( ){ double x ; FILE *ifp ;

/* try to open the file for reading, check if successful */ /* if it wasn't opened exit gracefully */ ifp = fopen("test_data.dat", "r") ; if (ifp == NULL) { printf ("Error opening test_data.dat\n"); exit (-1); } fscanf(ifp, "%lf", &x) ; /* read one double from the file

*/ fclose(ifp); /* close the file when finished */

/* check to see what you read */ printf("x = %.2f\n", x) ; return 0;}

Page 19: Programming in C

7/28/09

Detecting end-of-filewith fscanf

• When reading an unknown number of data When reading an unknown number of data elements from a file using elements from a file using fscanf( ), we need a we need a way to determine when the file has no more data way to determine when the file has no more data to read, i.e, we have reached the “end of file”.to read, i.e, we have reached the “end of file”.

• Fortunately, the return value from Fortunately, the return value from fscanf( ) holds the key. holds the key. fscanf( ) returns an integer returns an integer which is the number of data elements read from which is the number of data elements read from the file. If end-of-file is detected the integer the file. If end-of-file is detected the integer return value is the special value return value is the special value EOF

Page 20: Programming in C

7/28/09

EOF example code/* code snippet that reads an undetermined number of

integer student ages from a file and prints them out as an example of detecting EOF

*/FILE *inFile;int age;

inFile = fopen( “myfile”, “r” );if (inFile == NULL) { printf ("Error opening myFile\n"); exit (-1); }

while ( fscanf(infile, “%d”, &age ) != EOF )printf( “%d\n”, age );

fclose( inFile );

Page 21: Programming in C

7/28/09

fprintf.c/* fprintf.c *//* fprintf.c */#include <stdio.h>#include <stdio.h>#include <stdlib.h> /* exit */#include <stdlib.h> /* exit */int main ( )int main ( ){{ double pi = 3.14159 ;double pi = 3.14159 ; FILE *ofp ; *ofp ;

/* try to open the file for writing, check if successful *//* try to open the file for writing, check if successful */ /* if it wasn't exit gracefully *//* if it wasn't exit gracefully */ ofp = ofp = fopen("test.out", “w") ; if (ofp == NULL) {if (ofp == NULL) { printf ("Error opening test.out\n");printf ("Error opening test.out\n"); exit (-1);exit (-1); }}

/* write to the file using printf formats *//* write to the file using printf formats */ fprintf(ofp, “Hello World\n”); fprintf(ofp, “PI is defined as %6.5lf\n”, pi);

fclose(ofp); /* close the file when finished reading *//* close the file when finished reading */

return 0;return 0;} }

Page 22: Programming in C

7/28/09

fprintf vs printffscanf vs scanf

• Function prototypes are identical except that Function prototypes are identical except that fprintffprintf and and fscanffscanf require require FILE*FILE* parameter parameter

• Format strings identicalFormat strings identical• fscanffscanf, , fprintffprintf are more general are more general• printfprintf can be written using can be written using fprintffprintf

– fprintf( stdout, ....)

• Similarly, Similarly, scanfscanf can be written using can be written using fscanffscanf– fscanf( stdin, .... )

Page 23: Programming in C

7/28/09

Errors to stderr• Errors should be output to Errors should be output to stderr using using fprintf rather to rather to

stdout using using printf( )( )• Do thisDo this

– fprintf( stderr, “this is the error message\n” );

instead of thisinstead of this– printf( “this is the error message\n” );

• For exampleFor example

ofp = fopen("test.out", “w") ;

if (ofp == NULL) {

fprintf (stderr, "Error opening test.out\n");

exit (-1);

}