C: How to Program. Week /June/18

Size: px
Start display at page:

Download "C: How to Program. Week /June/18"

Transcription

1 C: How to Program Week /June/18 1

2 Chapter 11 File Processing Outline 11.1 Introduction 11.2 The Data Hierarchy 11.3 Files and Streams 11.4 Creating a Sequential Access File 11.5 Reading Data from a Sequential Access File 11.6 Random Access Files 11.7 Creating a Randomly Accessed File 11.8 Writing Data Randomly to a Randomly Accessed File 11.9 Reading Data Randomly from a Randomly Accessed File Case Study: A Transaction-Processing Program 2

3 11.1 Introduction Data files Can be created, updated, and processed by C programs Are used for permanent storage of large amounts of data Storage of data in variables and arrays is only temporary 3

4 Data Hierarchy: 11.2 The Data Hierarchy Bit smallest data item Value of 0 or 1 Byte 8 bits Used to store a character Decimal digits, letters, and special symbols Field group of characters conveying meaning Example: your name Record group of related fields Represented by a struct or a class Example: In a payroll system, a record for a particular employee that contained his/her identification number, name, address, etc. 4

5 11.2 The Data Hierarchy Data Hierarchy (continued): File group of related records Example: payroll file Database group of related files Judy Green Record Judy Field Byte (ASCII character J) Sally Black Tom Blue Judy Green File Iris Orange Randy Red 1 Bit Fig The data hierarchy 5

6 Data files 11.2 The Data Hierarchy Record key Identifies a record to facilitate the retrieval of specific records from a file Sequential file Records typically sorted by key 6

7 11.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) 7

8 FILEstructure File descriptor 11.3 Files and Streams 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 8

9 11.3 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 9

10 /* Fig. 11.3: fig11_03.c Create a sequential file */ #include <stdio.h> int main() { int account; /* account number */ char name[ 30 ]; /* account name */ double balance; /* account balance */ FILE *cfptr; /* cfptr = clients.dat file pointer */ /* fopen opens file. Exit program if unable to create file */ if ( ( cfptr = fopen( "clients.dat", "w" ) ) == NULL ) { printf( "File could not be opened\n" ); } /* end if */ else { printf( "Enter the account, name, and balance.\n" ); printf( "Enter EOF to end input.\n" ); printf( "? " ); scanf( "%d%s%lf", &account, name, &balance ); 10

11 /* write account, name and balance into file with fprintf */ while (!feof( stdin ) ) { fprintf( cfptr, "%d %s %.2f\n", account, name, balance ); printf( "? " ); scanf( "%d%s%lf", &account, name, &balance ); } /* end while */ fclose( cfptr ); /* fclose closes file */ } /* end else */ return 0; /* indicates successful termination */ } /* end main */ Enter the account, name, and balance. Enter EOF to end input.? 100 Jones 24.98? 200 Doe ? 300 White 0.00? 400 Stone ? 500 Rich ? ^Z 11

12 11.4 Creating a Sequential Access File C imposes no file structure No notion of records in a file Programmer must provide file structure Creating a File FILE *cfptr; Creates a FILE pointer called cfptr cfptr = fopen("clients.dat", "w"); Function fopen returns a FILE pointer to file specified Takes two arguments file to open and file open mode If open fails, NULL returned 12

13 11.4 Creating a Sequential Access File Computer system UNIX systems IBM PC and compatibles Macintosh Key combination <return> <ctrl> d <ctrl> z <ctrl> d Fig End-of-file key combinations for various popular computer systems. Opening an existing file for writing ( w ) when, in fact, the user wants to preserve the file discards the contents of the file without warning. Forgetting to open a file before attempting to reference it in a program is a logic error. 13

14 11.4 Creating a Sequential Access File 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) 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 14

15 11.4 Creating a Sequential Access File 3 User has access to this 1 cfptr = fopen( clients.dat, w ); fopen returns a pointer to a FILE structure (defined in <stdio.h>) newptr 2 FILE structure for clients.dat contents a descriptor, i.e., a small integer that is an index into the Open File Table 7 When the program issues an I/O call the program locates the descriptor (7) in the FILE structure, and uses the descriptor to find the FCB in the Open File Table. Only the OS has access to this Open File Table 0 1 : : 7 FCB for clients.dat : 4 The program calls an OS service that uses data in the FCB to control all input and output to the actual file on the disk. 15

16 11.4 Creating a Sequential Access File Mode Description 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. rb wb Open a file for reading in binary mode. Create a file for writing in binary mode. If the file already exists, discard the current contents. ab Append; open or create a file for writing at end of file in binary mode. rb+ Open a file for update (reading and writing) in binary mode. wb+ Create a file for update in binary mode. If the file already exists, discard the current contents. ab+ Append; open or create a file for update in binary mode; writing is done at the end of the file. Fig File open modes. 16

17 11.5 Reading Data from a Sequential Access File Reading a sequential access file Create a FILE pointer, link it to the file to read cfptr = fopen( "clients.dat", "r" ); Use fscanf to read from the file Like scanf, except first argument is a FILE pointer fscanf( cfptr, "%d%s%f", &accounnt, name, &balance ); 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( cfptr ) Repositions file position pointer to beginning of file (byte 0) 17

18 /* Fig. 11.7: fig11_07.c Reading and printing a sequential file */ #include <stdio.h> int main() { int account; /* account number */ char name[ 30 ]; /* account name */ double balance; /* account balance */ FILE *cfptr; /* cfptr = clients.dat file pointer */ /* fopen opens file; exits program if file cannot be opened */ if ( ( cfptr = fopen( "clients.dat", "r" ) ) == NULL ) { printf( "File could not be opened\n" ); } /* end if */ else { /* read account, name and balance from file */ printf( "%-10s%-13s%s\n", "Account", "Name", "Balance" ); fscanf( cfptr, "%d%s%lf", &account, name, &balance ); /* while not end of file */ while (!feof( cfptr ) ) { printf( "%-10d%-13s%7.2f\n", account, name, balance ); fscanf( cfptr, "%d%s%lf", &account, name, &balance ); } /* end while */ 18

19 fclose( cfptr ); /* fclose closes file */ } /* end else */ return 0; /* indicates successful termination */ } /* end main */ Account Name Balance 100 Jones Doe White Stone Rich Opening a nonexistent file for reading is an error. 19

20 /* Fig. 11.8: fig11_08.c Credit inquiry program */ #include <stdio.h> int main() { int request; /* request number */ int account; /* account number */ double balance; /* account balance */ char name[ 30 ]; /* account name */ FILE *cfptr; /* clients.dat file pointer */ /* fopen opens file; exits program if file cannot be opened */ if ( ( cfptr = fopen( "clients.dat", "r" ) ) == NULL ) { printf( "File could not be opened\n" ); } /* end if */ else { /* display request options */ printf( "Enter request\n" " 1 - List accounts with zero balances\n" " 2 - List accounts with credit balances\n" " 3 - List accounts with debit balances\n" " 4 - End of run\n? " ); scanf( "%d", &request ); 20

21 /* process user's request */ while ( request!= 4 ) { /* read account, name and balance from file */ fscanf( cfptr, "%d%s%lf", &account, name, &balance ); switch ( request ) { case 1: printf( "\naccounts with zero balances:\n" ); /* read file contents (until eof) */ while (!feof( cfptr ) ) { if ( balance == 0 ) { printf( "%-10d%-13s%7.2f\n", account, name, balance ); } /* end if */ /* read account, name and balance from file */ fscanf( cfptr, "%d%s%lf", &account, name, &balance ); } /* end while */ break; case 2: printf( "\naccounts with credit balances:\n" ); 21

22 /* read file contents (until eof) */ while (!feof( cfptr ) ) { if ( balance < 0 ) { printf( "%-10d%-13s%7.2f\n", account, name, balance ); } /* end if */ /* read account, name and balance from file */ fscanf( cfptr, "%d%s%lf", &account, name, &balance ); } /* end while */ break; case 3: printf( "\naccounts with debit balances:\n" ); /* read file contents (until eof) */ while (!feof( cfptr ) ) { if ( balance > 0 ) { printf( "%-10d%-13s%7.2f\n", account, name, balance ); } /* end if */ 22

23 /* read account, name and balance from file */ fscanf( cfptr, "%d%s%lf", &account, name, &balance ); } /* end while */ break; } /* end switch */ rewind( cfptr ); /* return cfptr to beginning of file */ printf( "\n? " ); scanf( "%d", &request ); } /* end while */ printf( "End of run.\n" ); fclose( cfptr ); /* fclose closes the file */ } /* end else */ return 0; /* indicates successful termination */ } /* end main */ 23

24 Enter request 1 - List accounts with zero balances 2 - List accounts with credit balances 3 - List accounts with debit balances 4 - End of run? 1 Accounts with zero balances: 300 White 0.00? 2 Accounts with credit balances: 400 Stone ? 3 Accounts with debit balances: 100 Jones Doe Rich ? 4 End of run. 24

25 11.5 Reading Data from a Sequential Access File Sequential access file Cannot be modified without the risk of destroying other data Fields can vary in size Different representation in files and screen than internal representation 1, 34, -890 are all ints, but have different sizes on disk 300 White Jones (old data in file) If we want to change White's name to Worthington, 300 Worthington White Jones Data gets overwritten 300 Worthington 0.00ones

26 Random access files 11.6 Random-Access Files Access individual records without searching through other records Instant access to records in a file Data can be inserted without destroying other data Data previously stored can be updated or deleted without overwriting Implemented using fixed length records Sequential files do not have fixed length records byte offsets 100 bytes 100 bytes 100 bytes 100 bytes 100 bytes 100 bytes 26

27 11.6 Random-Access Files Data in random access files Unformatted (stored as "raw bytes") All data of the same type (ints, for example) uses the same amount of memory All records of the same type have a fixed length Data not human readable 27

28 11.7 Creating a Randomly Accessed File 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 28

29 11.7 Creating a Randomly Accessed File Writing structs fwrite( &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 29

30 /* Fig : fig11_11.c Creating a random-access file sequentially */ #include <stdio.h> /* clientdata structure definition */ struct clientdata { int acctnum; /* account number */ char lastname[ 15 ]; /* account last name */ char firstname[ 10 ]; /* account first name */ double balance; /* account balance */ }; /* end structure clientdata */ int main() { int i; /* counter used to count from */ /* create clientdata with default information */ struct clientdata blankclient = { 0, "", "", 0.0 }; FILE *cfptr; /* credit.dat file pointer */ /* fopen opens the file; exits if file cannot be opened */ if ( ( cfptr = fopen( "credit.dat", "wb" ) ) == NULL ) { printf( "File could not be opened.\n" ); } /* end if */ else { 30

31 /* output 100 blank records to file */ for ( i = 1; i <= 100; i++ ) { fwrite( &blankclient, sizeof( struct clientdata ), 1, cfptr ); } /* end for */ fclose ( cfptr ); /* fclose closes the file */ } /* end else */ return 0; /* indicates successful termination */ } /* end main */ 31

32 11.8 Writing Data Randomly to a Randomly Accessed File 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 32

33 /* Fig : fig11_12.c Writing to a random access file */ #include <stdio.h> /* clientdata structure definition */ struct clientdata { int acctnum; /* account number */ char lastname[ 15 ]; /* account last name */ char firstname[ 10 ]; /* account first name */ double balance; /* account balance */ }; /* end structure clientdata */ int main() { /* create clientdata with default information */ struct clientdata Client ; FILE *cfptr; /* credit.dat file pointer */ /* fopen opens the file; exits if file cannot be opened */ if ( ( cfptr = fopen( "credit.dat", "rb+" ) ) == NULL ) { printf( "File could not be opened.\n" ); } /* end if */ else { 33

34 /* require user to specify account number */ printf( "Enter account number" " ( 1 to 100, 0 to end input )\n? " ); scanf( "%d", &client.acctnum ); /* user enters information, which is copied into file */ while ( client.acctnum!= 0 ) { /* user enters last name, first name and balance */ printf( "Enter lastname, firstname, balance\n? " ); /* set record lastname, firstname and balance value */ fscanf( stdin, "%s%s%lf", client.lastname, client.firstname, &client.balance ); /* seek position in file to user-specified record */ fseek( cfptr, ( client.acctnum - 1 ) * sizeof( struct clientdata ), SEEK_SET ); /* write user-specified information in file */ fwrite( &client, sizeof( struct clientdata ), 1, cfptr ); /* enable user to input another account number */ printf( "Enter account number\n? " ); scanf( "%d", &client.acctnum ); } /* end while */ 34

35 fclose( cfptr ); /* fclose closes the file */ } /* end else */ return 0; /* indicates successful termination */ } /* end main */ Enter account number ( 1 to 100, 0 to end input )? 37 Enter lastname, firstname, balance? Barker Doug 0.00 Enter account number? 29 Enter lastname, firstname, balance? Brown Nancy Enter account number? 96 Enter lastname, firstname, balance? Stone Sam Enter account number? 88 Enter lastname, firstname, balance? Smith Dave Enter account number? 33 Enter lastname, firstname, balance? Dunn Stacey Enter account number? 0 35

36 11.8 Writing Data Randomly to a Randomly Accessed File 36

37 11.9 Reading Data Randomly from a Randomly Accessed File fread Reads a specified number of bytes from a file into memory fread( &client, sizeof (struct clientdata), 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 37

38 /* Fig : fig11_15.c Reading a random access file sequentially */ #include <stdio.h> /* clientdata structure definition */ struct clientdata { int acctnum; /* account number */ char lastname[ 15 ]; /* account last name */ char firstname[ 10 ]; /* account first name */ double balance; /* account balance */ }; /* end structure clientdata */ int main() { /* create clientdata with default information */ struct clientdata blankclient = { 0, "", "", 0.0 }; FILE *cfptr; /* credit.dat file pointer */ /* fopen opens the file; exits if file cannot be opened */ if ( ( cfptr = fopen( "credit.dat", "rb" ) ) == NULL ) { printf( "File could not be opened.\n" ); } /* end if */ else { 38

39 printf( "%-6s%-16s%-11s%10s\n", "Acct", "Last Name", "First Name", "Balance" ); /* read all records from file (until eof) */ while (!feof( cfptr ) ) { fread( &client, sizeof( struct clientdata ), 1, cfptr ); /* display record */ if ( client.acctnum!= 0 ) { printf( "%-6d%-16s%-11s%10.2f\n", client.acctnum, client.lastname, client.firstname, client.balance ); } /* end if */ } /* end while */ fclose( cfptr ); /* fclose closes the file */ } /* end else */ return 0; /* indicates successful termination */ } /* end main */ 39

40 Acct Last Name First Name Balance 29 Brown Nancy Dunn Stacey Barker Doug Smith Dave Stone Sam

41 11.10 Case Study: A Transaction Processing Program This program Demonstrates using random access files to achieve instant access processing of a bank s account information We will Update existing accounts Add new accounts Delete accounts Store a formatted listing of all accounts in a text file 41

42 /* Fig : fig11_16.c This program reads a random access file sequentially, updates data already written to the file, creates new data to be placed in the file, and deletes data previously in the file. */ #include <stdio.h> /* clientdata structure definition */ struct clientdata { int acctnum; /* account number */ char lastname[ 15 ]; /* account last name */ char firstname[ 10 ]; /* account first name */ double balance; /* account balance */ }; /* end structure clientdata */ /* prototypes */ int enterchoice( void ); void textfile( FILE *readptr ); void updaterecord( FILE *fptr ); void newrecord( FILE *fptr ); void deleterecord( FILE *fptr ); int main() { FILE *cfptr; /* credit.dat file pointer */ int choice; /* user's choice */ 42

43 /* fopen opens the file; exits if file cannot be opened */ if ( ( cfptr = fopen( "credit.dat", "rb+" ) ) == NULL ) { printf( "File could not be opened.\n" ); } /* end if */ else { /* enable user to specify action */ while ( ( choice = enterchoice() )!= 5 ) { switch ( choice ) { /* create text file from record file */ case 1: textfile( cfptr ); break; /* update record */ case 2: updaterecord( cfptr ); break; /* create record */ case 3: newrecord( cfptr ); break; 43

44 /* delete existing record */ case 4: deleterecord( cfptr ); break; /* display message if user does not select valid choice */ default: printf( "Incorrect choice\n" ); break; } /* end switch */ } /* end while */ fclose( cfptr ); /* fclose closes the file */ } /* end else */ return 0; /* indicates successful termination */ } /* end main */ /* create formatted text file for printing */ void textfile( FILE *readptr ) { FILE *writeptr; /* accounts.txt file pointer */ 44

45 /* create clientdata with default information */ struct clientdata client = { 0, "", "", 0.0 }; /* fopen opens the file; exits if file cannot be opened */ if ( ( writeptr = fopen( "accounts.txt", "w" ) ) == NULL ) { printf( "File could not be opened.\n" ); } /* end if */ else { rewind( readptr ); /* sets pointer to beginning of file */ fprintf( writeptr, "%-6s%-16s%-11s%10s\n", "Acct", "Last Name", "First Name", "Balance" ); /* copy all records from random-access file into text file */ while (!feof( readptr ) ) { fread( &client, sizeof( struct clientdata ), 1, readptr ); /* write single record to text file */ if ( client.acctnum!= 0 ) { fprintf( writeptr, "%-6d%-16s%-11s%10.2f\n", client.acctnum, client.lastname, client.firstname, client.balance ); } /* end if */ } /* end while */ fclose( writeptr ); /* fclose closes the file */ } /* end else */ } /* end function textfile */ 45

46 /* update balance in record */ void updaterecord( FILE *fptr ) { int account; /* account number */ double transaction; /* transaction amount */ /* create clientdata with no information */ struct clientdata client = { 0, "", "", 0.0 }; /* obtain number of account to update */ printf( "Enter account to update ( ): " ); scanf( "%d", &account ); /* move file pointer to correct record in file */ fseek( fptr, ( account - 1 ) * sizeof( struct clientdata ), SEEK_SET ); /* read record from file */ fread( &client, sizeof( struct clientdata ), 1, fptr ); /* display error if account does not exist */ if ( client.acctnum == 0 ) { printf( "Acount #%d has no information.\n", account ); } /* end if */ else { /* update record */ 46

47 printf( "%-6d%-16s%-11s%10.2f\n\n", client.acctnum, client.lastname, client.firstname, client.balance ); /* request transaction amount from user */ printf( "Enter charge ( + ) or payment ( - ): " ); scanf( "%lf", &transaction ); client.balance += transaction; /* update record balance */ printf( "%-6d%-16s%-11s%10.2f\n", client.acctnum, client.lastname, client.firstname, client.balance ); /* move file pointer to correct record in file */ fseek( fptr, ( account - 1 ) * sizeof( struct clientdata ), SEEK_SET ); /* write updated record over old record in file */ fwrite( &client, sizeof( struct clientdata ), 1, fptr ); } /* end else */ } /* end function updaterecord */ 47

48 /* delete an existing record */ void deleterecord( FILE *fptr ) { struct clientdata client; /* stores record read from file */ struct clientdata blankclient = { 0, "", "", 0 }; /* blank client */ int accountnum; /* account number */ /* obtain number of account to delete */ printf( "Enter account number to delete ( ): " ); scanf( "%d", &accountnum ); /* move file pointer to correct record in file */ fseek( fptr, ( accountnum - 1 ) * sizeof( struct clientdata ), SEEK_SET ); /* read record from file */ fread( &client, sizeof( struct clientdata ), 1, fptr ); /* display error if record does not exist */ if ( client.acctnum == 0 ) { printf( "Account %d does not exist.\n", accountnum ); } /* end if */ else { /* delete record */ 48

49 /* move file pointer to correct record in file */ fseek( fptr, ( accountnum-1 ) * sizeof( struct clientdata ), SEEK_SET ); /* replace existing record with blank record */ fwrite( &blankclient, sizeof( struct clientdata ), 1, fptr ); } /* end else */ } /* end function deleterecord */ /* create and insert record */ void newrecord( FILE *fptr ) { /* create clientdata with default information */ struct clientdata client = { 0, "", "", 0.0 }; int accountnum; /* account number */ /* obtain number of account to create */ printf( "Enter new account number ( ): " ); scanf( "%d", &accountnum ); /* move file pointer to correct record in file */ fseek( fptr, ( accountnum - 1 ) * sizeof( struct clientdata ), SEEK_SET ); 49

50 /* read record from file */ fread( &client, sizeof( struct clientdata ), 1, fptr ); /* display error if account already exists */ if ( client.acctnum!= 0 ) { printf( "Account #%d already contains information.\n", client.acctnum ); } /* end if */ else { /* create record */ /* user enters last name, first name and balance */ printf( "Enter lastname, firstname, balance\n? " ); scanf( "%s%s%lf", &client.lastname, &client.firstname, &client.balance ); client.acctnum = accountnum; /* move file pointer to correct record in file */ fseek(fptr, (client.acctnum-1) * sizeof( struct clientdata ), SEEK_SET); /* insert record in file */ fwrite( &client, sizeof( struct clientdata ), 1, fptr ); } /* end else */ } /* end function newrecord */ 50

51 /* enable user to input menu choice */ int enterchoice( void ) { int menuchoice; /* variable to store user's choice */ /* display available options */ printf( "\nenter your choice\n" "1 - store a formatted text file of acounts called\n" " \"accounts.txt\" for printing\n" "2 - update an account\n" "3 - add a new account\n" "4 - delete an account\n" "5 - end program\n? " ); scanf( "%d", &menuchoice ); /* receive choice from user */ return menuchoice; } /* end function enterchoice */ 51

52 After choosing option 1 accounts.txt contains: Acct Last Name First Name Balance 29 Brown Nancy Dunn Stacey Barker Doug Smith Dave Stone Sam running option 2: Enter account to update ( ): Barker Doug 0.00 Enter charge ( + ) or payment ( - ): Barker Doug running option 2: Enter new account number ( ): 22 Enter lastname, firstname, balance? Johnston Sarah

53 Chapter 13 - The Preprocessor Outline 13.1 Introduction 13.2 The #include Preprocessor Directive 13.3 The #define Preprocessor Directive: Symbolic Constants 13.4 The #define Preprocessor Directive: Macros 13.5 Conditional Compilation 13.6 The #error and #pragma Preprocessor Directives 13.7 The # and ## Operators 13.8 Line Numbers 13.9 Predefined Symbolic Constants Assertions 53

54 13.1 Introduction Preprocessing Occurs before a program is compiled Inclusion of other files Definition of symbolic constants and macros Conditional compilation of program code Conditional execution of preprocessor directives Format of preprocessor directives Lines begin with # Only whitespace characters before directives on a line 54

55 13.2 The #include Preprocessor Directive #include Copy of a specified file included in place of the directive #include <filename> Searches standard library for file Use for standard library files #include "filename" Searches current directory, then standard library Use for user-defined files Used for: Programs with multiple source files to be compiled together Header file has common declarations and definitions (classes, structures, function prototypes) #include statement in each file 55

56 13.3 The #define Preprocessor Directive: Symbolic Constants #define Preprocessor directive used to create symbolic constants and macros Symbolic constants When program compiled, all occurrences of symbolic constant replaced with replacement text Format #define identifier replacement-text Example: #define PI Everything to right of identifier replaces text #define PI = Replaces PI with "= " Cannot redefine symbolic constants once they have been created 56

57 13.4 The #define Preprocessor Directive: Macros Macro Operation defined in #define A macro without arguments is treated like a symbolic constant A macro with arguments has its arguments substituted for replacement text, when the macro is expanded Performs a text substitution no data type checking The macro #define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) ) would cause area = CIRCLE_AREA( 4 ); to become area = ( * ( 4 ) * ( 4 ) ); 57

58 13.4 The #define Preprocessor Directive: Macros Use parenthesis Without them the macro #define CIRCLE_AREA( x ) PI * x * x would cause area = CIRCLE_AREA( c + 2 ); to become area = * c + 2 * c + 2; Multiple arguments #define RECTANGLE_AREA( x, y ) ( ( x ) * ( y ) ) would cause rectarea = RECTANGLE_AREA( a + 4, b + 7 ); to become rectarea = ( ( a + 4 ) * ( b + 7 ) ); 58

59 13.4 The #define Preprocessor Directive: Macros If the replacement text for a macro or symbolic constant is longer than the remainder of the line, a backslash ( \ ) must be placed at the end of the line. #undef Undefines a symbolic constant or macro If a symbolic constant or macro has been undefined it can later be redefined 59

60 13.5 Conditional Compilation Conditional compilation Control preprocessor directives and compilation Cast expressions, sizeof, enumeration constants cannot be evaluated in preprocessor directives Structure similar to if #if!defined( NULL ) #define NULL 0 #endif Determines if symbolic constant NULL has been defined If NULL is defined, defined( NULL ) evaluates to 1 If NULL is not defined, this function defines NULL to be 0 Every #if must end with #endif #ifdef short for #if defined( name ) #ifndef short for #if!defined( name ) 60

61 13.5 Conditional Compilation Other statements #elif equivalent of else if in an if statement #else equivalent of else in an if statement "Comment out" code Cannot use /*... */ Use #if 0 code commented out #endif To enable code, change 0 to 1 61

62 Debugging 13.5 Conditional Compilation #define DEBUG 1 #ifdef DEBUG cerr << "Variable x = " << x << endl; #endif Defining DEBUG to 1 enables code After code corrected, remove #define statement Debugging statements are now ignored 62

63 13.6 The #error and #pragma Preprocessor Directives #error tokens Tokens are sequences of characters separated by spaces "I like C++" has 3 tokens Displays a message including the specified tokens as an error message Stops preprocessing and prevents program compilation #pragma tokens Implementation defined action (consult compiler documentation) Pragmas not recognized by compiler are ignored 63

64 # 13.7 The # and ## Operators Causes a replacement text token to be converted to a string surrounded by quotes The statement #define HELLO( x ) printf( Hello, #x \n ); would cause HELLO( John ) to become printf( Hello, John \n ); Strings separated by whitespace are concatenated when using printf 64

65 13.7 The # and ## Operators ## Concatenates two tokens The statement #define TOKENCONCAT( x, y ) x ## y would cause TOKENCONCAT( O, K ) to become OK 65

66 #line 13.8 Line Numbers Renumbers subsequent code lines, starting with integer value File name can be included #line 100 "myfile.c" Lines are numbered from 100 beginning with next source code file Compiler messages will think that the error occurred in "myfile.c" Makes errors more meaningful Line numbers do not appear in source file 66

67 13.9 Predefined Symbolic Constants Four predefined symbolic constants Cannot be used in #define or #undef Sym b o lic c o n sta n t De sc rip tio n LINE FILE DATE TIME The line number of the current source code line (an integer constant). The presumed name of the source file (a string). The date the source file is compiled (a string of the form "Mmm dd yyyy" such as "Jan "). The time the source file is compiled (a string literal of the form "hh:mm:ss"). 67

68 13.10 Assertions assert macro Header <assert.h> Tests value of an expression If 0 (false) prints error message and calls abort Example: assert( x <= 10 ); If NDEBUG is defined All subsequent assert statements ignored #define NDEBUG 68

Chapter 11 File Processing

Chapter 11 File Processing 1 Chapter 11 File Processing Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 Chapter 11 File Processing Outline 11.1 Introduction 11.2 The Data Hierarchy 11.3

More information

Ch 11. C File Processing (review)

Ch 11. C File Processing (review) Ch 11 C File Processing (review) OBJECTIVES To create, read, write and update files. Sequential access file processing. Data Hierarchy Data Hierarchy: Bit smallest data item Value of 0 or 1 Byte 8 bits

More information

Lecture6 File Processing

Lecture6 File Processing 1 Lecture6 File Processing Dr. Serdar ÇELEBİ 2 Introduction The Data Hierarchy Files and Streams Creating a Sequential Access File Reading Data from a Sequential Access File Updating Sequential Access

More information

Lecture 8. Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Lecture 8. Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Lecture 8 Data Files Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To be able to create, read, write and update

More information

File Processing. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

File Processing. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan File Processing Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline 11.2 The Data Hierarchy 11.3 Files and Streams 11.4 Creating a Sequential

More information

Chapter 12. Files (reference: Deitel s chap 11) chap8

Chapter 12. Files (reference: Deitel s chap 11) chap8 Chapter 12 Files (reference: Deitel s chap 11) 20061025 chap8 Introduction of File Data files Can be created, updated, and processed by C programs Are used for permanent storage of large amounts of data

More information

C File Processing: One-Page Summary

C File Processing: One-Page Summary Chapter 11 C File Processing C File Processing: One-Page Summary #include int main() { int a; FILE *fpin, *fpout; if ( ( fpin = fopen( "input.txt", "r" ) ) == NULL ) printf( "File could not be

More information

ENG120. Misc. Topics

ENG120. Misc. Topics ENG120 Misc. Topics Topics Files in C Using Command-Line Arguments Typecasting Working with Multiple source files Conditional Operator 2 Files and Streams C views each file as a sequence of bytes File

More information

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 6/e Storage of data in variables and arrays is temporary such data is lost when a program terminates. Files are used for permanent retention of data. Computers store files on secondary

More information

STRUCTURES & FILE IO

STRUCTURES & FILE IO STRUCTURES & FILE IO Structures Collections of related variables (aggregates) under one name Can contain variables of different data types Commonly used to define records to be stored in files Combined

More information

OBJECT ORIENTED PROGRAMMING USING C++

OBJECT ORIENTED PROGRAMMING USING C++ OBJECT ORIENTED PROGRAMMING USING C++ Chapter 17 - The Preprocessor Outline 17.1 Introduction 17.2 The #include Preprocessor Directive 17.3 The #define Preprocessor Directive: Symbolic Constants 17.4 The

More information

Chapter 8 File Processing

Chapter 8 File Processing Chapter 8 File Processing Outline 1 Introduction 2 The Data Hierarchy 3 Files and Streams 4 Creating a Sequential Access File 5 Reading Data from a Sequential Access File 6 Updating Sequential Access Files

More information

BBM#101# #Introduc/on#to# Programming#I# Fall$2013,$Lecture$13$

BBM#101# #Introduc/on#to# Programming#I# Fall$2013,$Lecture$13$ BBM#101# #Introduc/on#to# Programming#I# Fall$2013,$Lecture$13$ Today#! File#Input#and#Output#! Strings#! Data!Files!! The!Data!Type!char!! Data!Hierarchy!! Characters!and!Integers!! Files!and!Streams!!

More information

BBM#101# #Introduc/on#to# Programming#I# Fall$2014,$Lecture$13$

BBM#101# #Introduc/on#to# Programming#I# Fall$2014,$Lecture$13$ BBM#101# #Introduc/on#to# Programming#I# Fall$2014,$Lecture$13$ Today#! File#Input#and#Output#! Strings#! Data&Files&! The&Data&Type&char&! Data&Hierarchy&! Characters&and&Integers&! Files&and&Streams&!

More information

BBM 101 Introduc/on to Programming I Fall 2013, Lecture 13

BBM 101 Introduc/on to Programming I Fall 2013, Lecture 13 BBM 101 Introduc/on to Programming I Fall 2013, Lecture 13 Instructors: Aykut Erdem, Erkut Erdem, Fuat Akal TAs: Yasin Sahin, Ahmet Selman Bozkir, Gultekin Isik 1 Today File Input and Output Strings Data

More information

Lecture 9: File Processing. Quazi Rahman

Lecture 9: File Processing. Quazi Rahman 60-141 Lecture 9: File Processing Quazi Rahman 1 Outlines Files Data Hierarchy File Operations Types of File Accessing Files 2 FILES Storage of data in variables, arrays or in any other data structures,

More information

Introduction to Computer Programming Lecture 18 Binary Files

Introduction to Computer Programming Lecture 18 Binary Files Introduction to Computer Programming Lecture 18 Binary Files Assist.Prof.Dr. Nükhet ÖZBEK Ege University Department of Electrical&Electronics Engineering nukhet.ozbek@ege.edu.tr 1 RECALL: Text File Handling

More information

Fundamentals of Programming. Lecture 15: C File Processing

Fundamentals of Programming. Lecture 15: C File Processing 1 Fundamentals of Programming Lecture 15: C File Processing Instructor: Fatemeh Zamani f_zamani@ce.sharif.edu Sharif University of Technology Computer Engineering Department The lectures of this course

More information

LAB 13 FILE PROCESSING

LAB 13 FILE PROCESSING LAB 13 FILE PROCESSING School of Computer and Communication Engineering Universiti Malaysia Perlis 1 1. OBJECTIVES: 1.1 To be able to create, read, write and update files. 1.2 To become familiar with sequential

More information

LAB 13 FILE PROCESSING

LAB 13 FILE PROCESSING LAB 13 FILE PROCESSING School of Computer and Communication Engineering Universiti Malaysia Perlis 1 1. OBJECTIVES: 1.1 To be able to create, read, write and update files. 1.2 To become familiar with sequential

More information

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060 CS 2060 Files and Streams Files are used for long-term storage of data (on a hard drive rather than in memory). Files and Streams Files are used for long-term storage of data (on a hard drive rather than

More information

Computer programming

Computer programming Computer programming "He who loves practice without theory is like the sailor who boards ship without a ruder and compass and never knows where he may cast." Leonardo da Vinci T.U. Cluj-Napoca - Computer

More information

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6 1. What is File management? In real life, we want to store data permanently so that later on we can retrieve it and reuse it. A file is a collection of bytes stored on a secondary storage device like hard

More information

UNIT IV-2. The I/O library functions can be classified into two broad categories:

UNIT IV-2. The I/O library functions can be classified into two broad categories: UNIT IV-2 6.0 INTRODUCTION Reading, processing and writing of data are the three essential functions of a computer program. Most programs take some data as input and display the processed data, often known

More information

Standard File Pointers

Standard File Pointers 1 Programming in C Standard File Pointers Assigned to console unless redirected Standard input = stdin Used by scan function Can be redirected: cmd < input-file Standard output = stdout Used by printf

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

Preprocessing directives are lines in your program that start with `#'. The `#' is followed by an identifier that is the directive name.

Preprocessing directives are lines in your program that start with `#'. The `#' is followed by an identifier that is the directive name. Unit-III Preprocessor: The C preprocessor is a macro processor that is used automatically by the C compiler to transform your program before actual compilation. It is called a macro processor because it

More information

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL. Files Files enable permanent storage of information C performs all input and output, including disk files, by means of streams Stream oriented data files are divided into two categories Formatted data

More information

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts Accessing Files in C Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

CSci 4061 Introduction to Operating Systems. Input/Output: High-level CSci 4061 Introduction to Operating Systems Input/Output: High-level I/O Topics First, cover high-level I/O Next, talk about low-level device I/O I/O not part of the C language! High-level I/O Hide device

More information

Fundamentals of Programming Session 28

Fundamentals of Programming Session 28 Fundamentals of Programming Session 28 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

System Software Experiment 1 Lecture 7

System Software Experiment 1 Lecture 7 System Software Experiment 1 Lecture 7 spring 2018 Jinkyu Jeong ( jinkyu@skku.edu) Computer Systems Laboratory Sungyunkwan University http://csl.skku.edu SSE3032: System Software Experiment 1, Spring 2018

More information

MARKS: Q1 /20 /15 /15 /15 / 5 /30 TOTAL: /100

MARKS: Q1 /20 /15 /15 /15 / 5 /30 TOTAL: /100 FINAL EXAMINATION INTRODUCTION TO ALGORITHMS AND PROGRAMMING II 03-60-141-01 U N I V E R S I T Y O F W I N D S O R S C H O O L O F C O M P U T E R S C I E N C E Winter 2014 Last Name: First Name: Student

More information

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character 1. What is File management? In real life, we want to store data permanently so that later on we can retrieve it and reuse it. A file is a collection of bytes stored on a secondary storage device like hard

More information

Program Design (II): Quiz2 May 18, 2009 Part1. True/False Questions (30pts) Part2. Multiple Choice Questions (40pts)

Program Design (II): Quiz2 May 18, 2009 Part1. True/False Questions (30pts) Part2. Multiple Choice Questions (40pts) Class: No. Name: Part1. True/False Questions (30pts) 1. Function fscanf cannot be used to read data from the standard input. ANS: False. Function fscanf can be used to read from the standard input by including

More information

PROGRAMMAZIONE I A.A. 2017/2018

PROGRAMMAZIONE I A.A. 2017/2018 PROGRAMMAZIONE I A.A. 2017/2018 INPUT/OUTPUT INPUT AND OUTPUT Programs must be able to write data to files or to physical output devices such as displays or printers, and to read in data from files or

More information

Fundamentals of Programming Session 27

Fundamentals of Programming Session 27 Fundamentals of Programming Session 27 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

File I/O. Arash Rafiey. November 7, 2017

File I/O. Arash Rafiey. November 7, 2017 November 7, 2017 Files File is a place on disk where a group of related data is stored. Files File is a place on disk where a group of related data is stored. C provides various functions to handle files

More information

Standard C Library Functions

Standard C Library Functions Demo lecture slides Although I will not usually give slides for demo lectures, the first two demo lectures involve practice with things which you should really know from G51PRG Since I covered much of

More information

Programming for Engineers C Preprocessor

Programming for Engineers C Preprocessor Programming for Engineers C Preprocessor ICEN 200 Spring 2018 Prof. Dola Saha 1 C Preprocessor The C preprocessor executes before a program is compiled. Some actions it performs are the inclusion of other

More information

C programming basics T3-1 -

C programming basics T3-1 - C programming basics T3-1 - Outline 1. Introduction 2. Basic concepts 3. Functions 4. Data types 5. Control structures 6. Arrays and pointers 7. File management T3-2 - 3.1: Introduction T3-3 - Review of

More information

CMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline.

CMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline. CMPE-013/L Outline File Processing File I/O Gabriel Hugh Elkaim Winter 2014 Files and Streams Open and Close Files Read and Write Sequential Files Read and Write Random Access Files Read and Write Random

More information

Input / Output Functions

Input / Output Functions CSE 2421: Systems I Low-Level Programming and Computer Organization Input / Output Functions Presentation G Read/Study: Reek Chapter 15 Gojko Babić 10-03-2018 Input and Output Functions The stdio.h contain

More information

File I/O. Preprocessor Macros

File I/O. Preprocessor Macros Computer Programming File I/O. Preprocessor Macros Marius Minea marius@cs.upt.ro 4 December 2017 Files and streams A file is a data resource on persistent storage (e.g. disk). File contents are typically

More information

CSI 402 Lecture 2 Working with Files (Text and Binary)

CSI 402 Lecture 2 Working with Files (Text and Binary) CSI 402 Lecture 2 Working with Files (Text and Binary) 1 / 30 AQuickReviewofStandardI/O Recall that #include allows use of printf and scanf functions Example: int i; scanf("%d", &i); printf("value

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

Systems Programming. 08. Standard I/O Library. Alexander Holupirek

Systems Programming. 08. Standard I/O Library. Alexander Holupirek Systems Programming 08. Standard I/O Library Alexander Holupirek Database and Information Systems Group Department of Computer & Information Science University of Konstanz Summer Term 2008 Last lecture:

More information

Unit 4 Preprocessor Directives

Unit 4 Preprocessor Directives 1 What is pre-processor? The job of C preprocessor is to process the source code before it is passed to the compiler. Source Code (test.c) Pre-Processor Intermediate Code (test.i) Compiler The pre-processor

More information

CS240: Programming in C

CS240: Programming in C CS240: Programming in C Lecture 13 si 14: Unix interface for working with files. Cristina Nita-Rotaru Lecture 13/Fall 2013 1 Working with Files (I/O) File system: specifies how the information is organized

More information

Chapter 7: Preprocessing Directives

Chapter 7: Preprocessing Directives Chapter 7: Preprocessing Directives Outline We will only cover these topics in Chapter 7, the remain ones are optional. Introduction Symbolic Constants and Macros Source File Inclusion Conditional Compilation

More information

Computer Programming Unit v

Computer Programming Unit v READING AND WRITING CHARACTERS We can read and write a character on screen using printf() and scanf() function but this is not applicable in all situations. In C programming language some function are

More information

C PROGRAMMING. Characters and Strings File Processing Exercise

C PROGRAMMING. Characters and Strings File Processing Exercise C PROGRAMMING Characters and Strings File Processing Exercise CHARACTERS AND STRINGS A single character defined using the char variable type Character constant is an int value enclosed by single quotes

More information

UNIT-V CONSOLE I/O. This section examines in detail the console I/O functions.

UNIT-V CONSOLE I/O. This section examines in detail the console I/O functions. UNIT-V Unit-5 File Streams Formatted I/O Preprocessor Directives Printf Scanf A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage

More information

Chapter 12. Text and Binary File Processing. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved.

Chapter 12. Text and Binary File Processing. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved. Chapter 12 Text and Binary File Processing Instructor: Öğr. Gör. Okan Vardarlı Copyright 2004 Pearson Addison-Wesley. All rights reserved. Objectives We will explore the use of standard input, standard

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Stack/Queue - File Processing Lecture 10 March 29, 2005 Introduction 2 Storage of data Arrays, variables are temporary Files are permanent Magnetic disk, optical

More information

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files CS113: Lecture 7 Topics: The C Preprocessor I/O, Streams, Files 1 Remember the name: Pre-processor Most commonly used features: #include, #define. Think of the preprocessor as processing the file so as

More information

25.2 Opening and Closing a File

25.2 Opening and Closing a File Lecture 32 p.1 Faculty of Computer Science, Dalhousie University CSCI 2132 Software Development Lecture 32: Dynamically Allocated Arrays 26-Nov-2018 Location: Chemistry 125 Time: 12:35 13:25 Instructor:

More information

C mini reference. 5 Binary numbers 12

C mini reference. 5 Binary numbers 12 C mini reference Contents 1 Input/Output: stdio.h 2 1.1 int printf ( const char * format,... );......................... 2 1.2 int scanf ( const char * format,... );.......................... 2 1.3 char

More information

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection 1 Files 1.1 File functions Opening Files : The function fopen opens a file and returns a FILE pointer. FILE *fopen( const char * filename, const char * mode ); The allowed modes for fopen are as follows

More information

Have examined process Creating program Have developed program Written in C Source code

Have examined process Creating program Have developed program Written in C Source code Preprocessing, Compiling, Assembling, and Linking Introduction In this lesson will examine Architecture of C program Introduce C preprocessor and preprocessor directives How to use preprocessor s directives

More information

C Basics And Concepts Input And Output

C Basics And Concepts Input And Output C Basics And Concepts Input And Output Report Working group scientific computing Department of informatics Faculty of mathematics, informatics and natural sciences University of Hamburg Written by: Marcus

More information

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12 BIL 104E Introduction to Scientific and Engineering Computing Lecture 12 Files v.s. Streams In C, a file can refer to a disk file, a terminal, a printer, or a tape drive. In other words, a file represents

More information

Sistemas Operativos /2016 Support Document N o 1. Files, Pipes, FIFOs, I/O Redirection, and Unix Sockets

Sistemas Operativos /2016 Support Document N o 1. Files, Pipes, FIFOs, I/O Redirection, and Unix Sockets Universidade de Coimbra Departamento de Engenharia Electrotécnica e de Computadores Sistemas Operativos - 2015/2016 Support Document N o 1 Files, Pipes, FIFOs, I/O Redirection, and Unix Sockets 1 Objectives

More information

Chapter 14 File Processing

Chapter 14 File Processing Chapter 14 File Processing Outline 14.1 Introd uction 14.2 The Data Hie rarchy 14.3 File s and Stre am s 14.4 Cre ating a Se q ue ntialacce ss File 14.5 Re ad ing Data from a Se q ue ntialacce ss File

More information

Chapter 14 - Advanced C Topics

Chapter 14 - Advanced C Topics Chapter 14 - Advanced C Topics Outline 14.1 Introduction 14.2 Redirecting Input/Output on UNIX and DOS Systems 14.3 Variable-Length Argument Lists 14.4 Using Command-Line Arguments 14.5 Notes on Compiling

More information

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments File I/O Content Input Output Devices File access Function of File I/O Redirection Command-line arguments UNIX and C language C is a general-purpose, high-level language that was originally developed by

More information

C++ Programming Lecture 10 File Processing

C++ Programming Lecture 10 File Processing C++ Programming Lecture 10 File Processing By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department Outline Introduction. The Data Hierarchy. Files and Streams. Creating a Sequential

More information

Programming & Data Structure

Programming & Data Structure File Handling Programming & Data Structure CS 11002 Partha Bhowmick http://cse.iitkgp.ac.in/ pb CSE Department IIT Kharagpur Spring 2012-2013 File File Handling File R&W argc & argv (1) A file is a named

More information

C for Engineers and Scientists: An Interpretive Approach. Chapter 14: File Processing

C for Engineers and Scientists: An Interpretive Approach. Chapter 14: File Processing Chapter 14: File Processing Files and Streams C views each file simply as a sequential stream of bytes. It ends as if there is an end-of-file marker. The data structure FILE, defined in stdio.h, stores

More information

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS A mini Quiz 2 Consider the following struct definition struct name{ int a; float b; }; Then somewhere in main() struct name *ptr,p; ptr=&p;

More information

Day14 A. Young W. Lim Thr. Young W. Lim Day14 A Thr 1 / 14

Day14 A. Young W. Lim Thr. Young W. Lim Day14 A Thr 1 / 14 Day14 A Young W. Lim 2017-11-02 Thr Young W. Lim Day14 A 2017-11-02 Thr 1 / 14 Outline 1 Based on 2 C Strings (1) Characters and Strings Unformatted IO Young W. Lim Day14 A 2017-11-02 Thr 2 / 14 Based

More information

Contents. A Review of C language. Visual C Visual C++ 6.0

Contents. A Review of C language. Visual C Visual C++ 6.0 A Review of C language C++ Object Oriented Programming Pei-yih Ting NTOU CS Modified from www.cse.cuhk.edu.hk/~csc2520/tuto/csc2520_tuto01.ppt 1 2 3 4 5 6 7 8 9 10 Double click 11 12 Compile a single source

More information

2009 S2 COMP File Operations

2009 S2 COMP File Operations 2009 S2 COMP1921 9. File Operations Oliver Diessel odiessel@cse.unsw.edu.au Last updated: 16:00 22 Sep 2009 9. File Operations Topics to be covered: Streams Text file operations Binary file operations

More information

C-Refresher: Session 10 Disk IO

C-Refresher: Session 10 Disk IO C-Refresher: Session 10 Disk IO Arif Butt Summer 2017 I am Thankful to my student Muhammad Zubair bcsf14m029@pucit.edu.pk for preparation of these slides in accordance with my video lectures at http://www.arifbutt.me/category/c-behind-the-curtain/

More information

EECS2031. Modifiers. Data Types. Lecture 2 Data types. signed (unsigned) int long int long long int int may be omitted sizeof()

EECS2031. Modifiers. Data Types. Lecture 2 Data types. signed (unsigned) int long int long long int int may be omitted sizeof() Warning: These notes are not complete, it is a Skelton that will be modified/add-to in the class. If you want to us them for studying, either attend the class or get the completed notes from someone who

More information

Day14 A. Young W. Lim Tue. Young W. Lim Day14 A Tue 1 / 15

Day14 A. Young W. Lim Tue. Young W. Lim Day14 A Tue 1 / 15 Day14 A Young W. Lim 2017-12-26 Tue Young W. Lim Day14 A 2017-12-26 Tue 1 / 15 Outline 1 Based on 2 C Strings (1) Characters and Strings Unformatted IO Young W. Lim Day14 A 2017-12-26 Tue 2 / 15 Based

More information

C Programming Language

C Programming Language C Programming Language File Input/Output Dr. Manar Mohaisen Office: F208 Email: manar.subhi@kut.ac.kr Department of EECE Review of the Precedent Lecture Arrays and Pointers Class Objectives What is a File?

More information

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

COMP322 - Introduction to C++ Lecture 02 - Basics of C++ COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.

More information

Lecture 9. Introduction

Lecture 9. Introduction Lecture 9 File Processing Streams Stream I/O template hierarchy Create, update, process files Sequential and random access Formatted and raw processing Namespaces Lec 9 Programming in C++ 1 Storage of

More information

Fundamentals of Programming Session 25

Fundamentals of Programming Session 25 Fundamentals of Programming Session 25 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Physical Files and Logical Files. Opening Files. Chap 2. Fundamental File Processing Operations. File Structures. Physical file.

Physical Files and Logical Files. Opening Files. Chap 2. Fundamental File Processing Operations. File Structures. Physical file. File Structures Physical Files and Logical Files Chap 2. Fundamental File Processing Operations Things you have to learn Physical files and logical files File processing operations: create, open, close,

More information

Input/Output and the Operating Systems

Input/Output and the Operating Systems Input/Output and the Operating Systems Fall 2015 Jinkyu Jeong (jinkyu@skku.edu) 1 I/O Functions Formatted I/O printf( ) and scanf( ) fprintf( ) and fscanf( ) sprintf( ) and sscanf( ) int printf(const char*

More information

C Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review

C Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review CS 2060 Variables Variables are statically typed. Variables must be defined before they are used. You only specify the type name when you define the variable. int a, b, c; float d, e, f; char letter; //

More information

Introduction to Computer and Program Design. Lesson 6. File I/O. James C.C. Cheng Department of Computer Science National Chiao Tung University

Introduction to Computer and Program Design. Lesson 6. File I/O. James C.C. Cheng Department of Computer Science National Chiao Tung University Introduction to Computer and Program Design Lesson 6 File I/O James C.C. Cheng Department of Computer Science National Chiao Tung University File System in OS Microsoft Windows Filename DriveID : /DirctoryName/MainFileName.ExtensionName

More information

Advanced C Programming Topics

Advanced C Programming Topics Introductory Medical Device Prototyping Advanced C Programming Topics, http://saliterman.umn.edu/ Department of Biomedical Engineering, University of Minnesota Operations on Bits 1. Recall there are 8

More information

Organization of a file

Organization of a file File Handling 1 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example: Consider keeping students records 100 students

More information

The Design of C: A Rational Reconstruction (cont.)

The Design of C: A Rational Reconstruction (cont.) The Design of C: A Rational Reconstruction (cont.) 1 Goals of this Lecture Recall from last lecture Help you learn about: The decisions that were available to the designers of C The decisions that were

More information

Pointers and File Handling

Pointers and File Handling 1 Pointers and File Handling From variables to their addresses Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 2 Basics of Pointers INDIAN INSTITUTE OF TECHNOLOGY

More information

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch. 1 Quick review of previous lecture Ch6 Structure Ch7 I/O EECS2031 Software Tools C - Structures, Unions, Enums & Typedef (K&R Ch.6) Structures Basics: Declaration and assignment Structures and functions

More information

COMP322 - Introduction to C++

COMP322 - Introduction to C++ COMP322 - Introduction to C++ Winter 2011 Lecture 2 - Language Basics Milena Scaccia School of Computer Science McGill University January 11, 2011 Course Web Tools Announcements, Lecture Notes, Assignments

More information

Files. Programs and data are stored on disk in structures called files Examples. a.out binary file lab1.c - text file term-paper.

Files. Programs and data are stored on disk in structures called files Examples. a.out binary file lab1.c - text file term-paper. File IO part 2 Files Programs and data are stored on disk in structures called files Examples a.out binary file lab1.c - text file term-paper.doc - binary file Overview File Pointer (FILE *) Standard:

More information

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 18 I/O in C Standard C Library I/O commands are not included as part of the C language. Instead, they are part of the Standard C Library. A collection of functions and macros that must be implemented

More information

mywbut.com 12 File Input/Output

mywbut.com 12 File Input/Output 12 File Input/Output Data Organization File Operations Opening a File Reading from a File Trouble in Opening a File Closing the File Counting Characters, Tabs, Spaces, A File-copy Program Writing to a

More information

EM108 Software Development for Engineers

EM108 Software Development for Engineers EE108 Section 4 Files page 1 of 14 EM108 Software Development for Engineers Section 4 - Files 1) Introduction 2) Operations with Files 3) Opening Files 4) Input/Output Operations 5) Other Operations 6)

More information

CE Lecture 11

CE Lecture 11 Izmir Institute of Technology CE - 104 Lecture 11 References: - C: A software Engineering Approach 1 In this course you will learn Input and Output Sorting Values 2 Input and Output Opening and Closing

More information

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco CS 326 Operating Systems C Programming Greg Benson Department of Computer Science University of San Francisco Why C? Fast (good optimizing compilers) Not too high-level (Java, Python, Lisp) Not too low-level

More information

Problem Solving and 'C' Programming

Problem Solving and 'C' Programming Problem Solving and 'C' Programming Targeted at: Entry Level Trainees Session 15: Files and Preprocessor Directives/Pointers 2007, Cognizant Technology Solutions. All Rights Reserved. The information contained

More information

Goals of C "" The Goals of C (cont.) "" Goals of this Lecture"" The Design of C: A Rational Reconstruction"

Goals of C  The Goals of C (cont.)  Goals of this Lecture The Design of C: A Rational Reconstruction Goals of this Lecture The Design of C: A Rational Reconstruction Help you learn about: The decisions that were available to the designers of C The decisions that were made by the designers of C Why? Learning

More information

The Design of C: A Rational Reconstruction (cont.)" Jennifer Rexford!

The Design of C: A Rational Reconstruction (cont.) Jennifer Rexford! The Design of C: A Rational Reconstruction (cont.)" Jennifer Rexford! 1 Goals of this Lecture"" Help you learn about:! The decisions that were available to the designers of C! The decisions that were made

More information

File IO and command line input CSE 2451

File IO and command line input CSE 2451 File IO and command line input CSE 2451 File functions Open/Close files fopen() open a stream for a file fclose() closes a stream One character at a time: fgetc() similar to getchar() fputc() similar to

More information