Lec11 Ec11 Misc

25
ENG120 Misc. Topics

description

computation c

Transcript of Lec11 Ec11 Misc

ENG120

Misc. Topics

Topics

• Files in C• Using Command-Line Arguments• Typecasting• Working with Multiple source files• Conditional Operator

2

3

Files and Streams• C views each file as a sequence of bytes

– File ends with the end-of-file marker• Or, file ends at a specified byte

• Stream created when a file is opened– Provide communication channel between files and

programs– Opening a file returns a pointer to a FILE structure

• Example file pointers:• stdin - standard input (keyboard)• stdout - standard output (screen)• stderr - standard error (screen)

• FILE structure– File descriptor

• Index into operating system array called the open file table

– File Control Block (FCB)• Found in every array element, system uses it to administer the file

4

Files and Streams• Read/Write functions in standard library

– fgetc• Reads one character from a file• Takes a FILE pointer as an argument• fgetc( stdin ) equivalent to getchar()

– fputc• Writes one character to a file• Takes a FILE pointer and a character to write as an argument• fputc( 'a', stdout ) equivalent to putchar( 'a' )

– fgets• Reads a line from a file

– fputs• Writes a line to a file

– fscanf / fprintf• File processing equivalents of scanf and printf

5

Dealing with Files• C imposes no file structure

– No notion of records in a file– Programmer must provide file structure

• Creating a File– FILE *myPtr;

• Creates a FILE pointer called myPtr– myPtr = fopen("myFile.dat", openmode);

• Function fopen returns a FILE pointer to file specified• Takes two arguments – file to open and file open mode• If open fails, NULL returned

– fprintf• Used to print to a file• Like printf, except first argument is a FILE pointer (pointer to the

file you want to print in)

6

Dealing with Files– feof( FILE pointer )

• Returns true if end-of-file indicator (no more data to process) is set for the specified file

– fclose( FILE pointer )• Closes specified file• Performed automatically when program ends• Good practice to close files explicitly

• Details– Programs may process no files, one file, or many files– Each file must have a unique name and should have

its own pointer

7

Open Modes

Mode Desc ription r Open a file for reading. w Create a file for writing. If the file already exists,

discard the current contents. a Append; open or create a file for writing at end of file. r+ Open a file for update (reading and writing). w+ Create a file for update. If the file already exists,

discard the current contents. a+ Append; open or create a file for update; writing is

done at the end of the file.

8

3 #include <stdio.h>45 int main()6 { 7 int account;8 char name[ 30 ];9 double balance;10 FILE *cfPtr; /* cfPtr = clients.dat file pointer */1112 if ( ( cfPtr = fopen( "clients.dat", "w" ) ) == NULL )13 printf( "File could not be opened\n" );14 else { 15 printf( "Enter the account, name, and balance.\n" );16 printf( "Enter EOF to end input.\n" );17 printf( "? " );18 scanf( "%d%s%lf", &account, name, &balance );1920 while ( !feof( stdin ) ) { 21 fprintf( cfPtr, "%d %s %.2f\n", 22 account, name, balance );23 printf( "? " );24 scanf( "%d%s%lf", &account, name, &balance );25 }2627 fclose( cfPtr );28 }2930 return 0;31 }

9

Enter the account, name, and balance.Enter EOF to end input.? 100 Jones 24.98? 200 Doe 345.67? 300 White 0.00? 400 Stone -42.16? 500 Rich 224.62?

10

Reading Data from a Sequential Access File

• Reading a sequential access file– Create a FILE pointer, link it to the file to read

myPtr = fopen( "myFile.dat", "r" );– Use fscanf to read from the file

• Like scanf, except first argument is a FILE pointerfscanf( myPtr, "%d%s%f", &myInt, &myString, &myFloat );

– Data read from beginning to end– File position pointer

• Indicates number of next byte to be read / written• Not really a pointer, but an integer value (specifies byte location)• Also called byte offset

– rewind( myPtr )• Repositions file position pointer to beginning of file (byte 0)

1 /* Fig. 11.7: fig11_07.c2 Reading and printing a sequential file */3 #include <stdio.h>45 int main()6 { 7 int account;8 char name[ 30 ];9 double balance;10 FILE *cfPtr; /* cfPtr = clients.dat file pointer */1112 if ( ( cfPtr = fopen( "clients.dat", "r" ) ) == NULL )13 printf( "File could not be opened\n" );14 else { 15 printf( "%-10s%-13s%s\n", "Account", "Name", "Balance" );16 fscanf( cfPtr, "%d%s%lf", &account, name, &balance );1718 while ( !feof( cfPtr ) ) { 19 printf( "%-10d%-13s%7.2f\n", account, name, balance );20 fscanf( cfPtr, "%d%s%lf", &account, name, &balance );21 }2223 fclose( cfPtr );24 }2526 return 0;27 }Account Name Balance100 Jones 24.98200 Doe 345.67300 White 0.00400 Stone -42.16500 Rich 224.62

12

Unformatted File I/O

• Unformatted I/O functions– fwrite

• Transfer bytes from a location in memory to a file– fread

• Transfer bytes from a file to a location in memory– Example:

fwrite( &number, sizeof( int ), 1, myPtr );• &number – Location to transfer bytes from• sizeof( int ) – Number of bytes to transfer• 1 – For arrays, number of elements to transfer

– In this case, "one element" of an array is being transferred• myPtr – File to transfer to or from

13

Unformatted File I/O

• Writing structsfwrite( &myObject, sizeof (struct myStruct), 1, myPtr );

– sizeof – returns size in bytes of object in parentheses

• To write several array elements– Pointer to array as first argument– Number of elements to write as third argument

14

1 /* Fig. 11.11: fig11_11.c2 Creating a randomly accessed file sequentially */3 #include <stdio.h>45 struct clientData { 6 int acctNum;7 char lastName[ 15 ];8 char firstName[ 10 ];9 double balance;10 };1112 int main()13 { 14 int i;15 struct clientData blankClient = { 0, "", "", 0.0 };16 FILE *cfPtr;1718 if ( ( cfPtr = fopen( "credit.dat", "w" ) ) == NULL )19 printf( "File could not be opened.\n" );20 else { 2122 for ( i = 1; i <= 100; i++ )23 fwrite( &blankClient, 24 sizeof( struct clientData ), 1, cfPtr );2526 fclose( cfPtr );27 }2829 return 0;30 }

15

Random Access

• fseek– Sets file position pointer to a specific position– fseek( pointer, offset, symbolic_constant);

• pointer – pointer to file• offset – file position pointer (0 is first location)• symbolic_constant – specifies where in file we are

reading from• SEEK_SET – seek starts at beginning of file• SEEK_CUR – seek starts at current location in file• SEEK_END – seek starts at end of file

16

Unformatted File Read

• fread– Reads a specified number of bytes from a file into

memoryfread( &client, sizeof (structclientData), 1, myPtr );

– Can read several fixed-size array elements• Provide pointer to array• Indicate number of elements to read

– To read multiple elements, specify in third argument

Using Command-Line Arguments• Pass arguments to main on DOS or UNIX

– Define main asint main( int argc, char *argv[] )

– int argc• Number of arguments passed

– char *argv[]• Array of strings• Has names of arguments in order

– argv[ 0 ] is first argument– Example: $ copy input output

• argc: 3• argv[ 0 ]: "copy"• argv[ 1 ]: "input"• argv[ 2 ]: "output"

17

1 /* Fig. 14.3: fig14_03.c2 Using command-line arguments */3 #include <stdio.h>45 int main( int argc, char *argv[] )6 { 7 FILE *inFilePtr, *outFilePtr;8 int c;910 if ( argc != 3 )11 printf( "Usage: copy infile outfile\n" );12 else13 if ( ( inFilePtr = fopen( argv[ 1 ], "r" ) ) != NULL )1415 if ( ( outFilePtr = fopen( argv[ 2 ], "w" ) ) != NULL )1617 while ( ( c = fgetc( inFilePtr ) ) != EOF )18 fputc( c, outFilePtr );1920 else21 printf( "File \"%s\" could not be opened\n", argv[ 2 ] );2223 else24 printf( "File \"%s\" could not be opened\n", argv[ 1 ] );2526 return 0;27 }

Notice argc and argv[] in main

argv[1] is the second argument, and is being read.

argv[2] is the third argument, and is being written to.

Loop until End Of File. fgetc a character from inFilePtr and fputc it into outFilePtr.

Typecasting in C

• You can use type casts to explicitly convert types.

• Syntax:– ( type-name ) cast-expression

• Example:– int *p=(int *) malloc(20);– int x = (int) 3.5;

19

Legal Typecasts

20

Implicit Casting(automatic transformation)

• works in a way that a variable (operand) of data type that is smaller in length (than data type of second variable) (operand), transforming internally to variable of data type with longer number length. It may sound mixed up, but here is an example:

• short int -> int -> unsigned int ->long int -> unsigned long int -> float -> double-> long double

21

Implicit CastingExample

int a;unsigned long b;float f, g;double d;g = a + f; // a transforms to floatd = a + b; // a and b transform to unsigned long,

// adding result is produced in unsigned // long domain and then the result type // unsigned long is transformed // to double

22

Notes on Compiling Multiple-Source-File Programs

• Programs with multiple source files– Function definition must be in one file (cannot be split up)– Global variables accessible to functions in same file

• Global variables must be defined in every file in which they are used– Example:

• If integer myGlobal is defined in one file• To use it in another file you must include the statement

extern int myGlobal;– extern

• States that the variable is defined in another file– Function prototypes can be used in other files without an extern

statement• Have a prototype in each file that uses the function

23

Notes on Compiling Multiple-Source-File Programs

• Keyword static– Specifies that variables can only be used in the file

in which they are defined

• Programs with multiple source files – Tedious to compile everything if small changes

have been made to only one file– Can recompile only the changed files– Procedure varies on system

• UNIX: make utility

24

Conditional (? :) Operator

average = (n > 0) ? sum / n : 0;

Equivalent to:

if(n > 0) average = sum / n;

else average = 0;

25