ENG120. Misc. Topics

Similar documents
Lecture6 File Processing

C File Processing: One-Page Summary

Ch 11. C File Processing (review)

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

Chapter 11 File Processing

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

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

C: How to Program. Week /June/18

STRUCTURES & FILE IO

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

Chapter 8 File Processing

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

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

Computer programming

Lecture 9: File Processing. Quazi Rahman

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

Fundamentals of Programming. Lecture 15: C File Processing

LAB 13 FILE PROCESSING

LAB 13 FILE PROCESSING

Introduction to Computer Programming Lecture 18 Binary Files

System Software Experiment 1 Lecture 7

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

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

C programming basics T3-1 -

C PROGRAMMING. Characters and Strings File Processing Exercise

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

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

Input / Output Functions

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

File IO and command line input CSE 2451

Standard C Library Functions

Chapter 14 - Advanced C Topics

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

CS240: Programming in C

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

PROGRAMMAZIONE I A.A. 2017/2018

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

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

C Basics And Concepts Input And Output

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

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

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

Standard File Pointers

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

File (1A) Young Won Lim 11/25/16

Intermediate Programming, Spring 2017*

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

UNIX System Programming

C-Refresher: Session 10 Disk IO

Input/Output and the Operating Systems

C mini reference. 5 Binary numbers 12

Organization of a file

25.2 Opening and Closing a File

Introduction to file management

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

LANGUAGE OF THE C. C: Part 6. Listing 1 1 #include <stdio.h> 2 3 int main(int argc, char *argv[]) PROGRAMMING

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

fopen() fclose() fgetc() fputc() fread() fwrite()

CSI 402 Lecture 2 (More on Files) 2 1 / 20

Computer Programming Unit v

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

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

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

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

2009 S2 COMP File Operations

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

File I/O. Preprocessor Macros

The Design of C: A Rational Reconstruction: Part 2

Continued from previous lecture

EM108 Software Development for Engineers

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

Programming in C. Session 8. Seema Sirpal Delhi University Computer Centre

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

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

Goals of this Lecture

What Is Operating System? Operating Systems, System Calls, and Buffered I/O. Academic Computers in 1983 and Operating System

CS 350 : COMPUTER SYSTEM CONCEPTS SAMPLE TEST 2 (OPERATING SYSTEMS PART) Student s Name: MAXIMUM MARK: 100 Time allowed: 70 minutes

I/O Management! Goals of this Lecture!

I/O Management! Goals of this Lecture!

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

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

CS 261 Fall Mike Lam, Professor. Structs and I/O

Programming & Data Structure

CSE 410: Systems Programming

DATA STRUCTURES USING C

CSCI 171 Chapter Outlines

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

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

C Programming 1. File Access. Goutam Biswas. Lect 29

Lecture 8: Structs & File I/O

Data File and File Handling

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

CE Lecture 11

IO = Input & Output 2

CAAM 420 Notes Chapter 2: The C Programming Language

DS: CS Computer Sc & Engg: IIT Kharagpur 1. File Access. Goutam Biswas. ect 29

UNIX input and output

Pointers cause EVERYBODY problems at some time or another. char x[10] or char y[8][10] or char z[9][9][9] etc.

Naked C Lecture 6. File Operations and System Calls

UNIX Shell. The shell sits between you and the operating system, acting as a command interpreter

Transcription:

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 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 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 4

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) 5

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 6

Open Modes 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. 7

3 #include <stdio.h> 4 5 int main() 6 { 7 int account; 8 char name[ 30 ]; 9 double balance; 10 FILE *cfptr; /* cfptr = clients.dat file pointer */ 11 12 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 ); 19 20 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 } 26 27 fclose( cfptr ); 28 } 29 30 return 0; 31 } 8

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

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 pointer fscanf( 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) 10

1 /* Fig. 11.7: fig11_07.c 2 Reading and printing a sequential file */ 3 #include <stdio.h> 4 5 int main() 6 { 7 int account; 8 char name[ 30 ]; 9 double balance; 10 FILE *cfptr; /* cfptr = clients.dat file pointer */ 11 12 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 ); 17 18 while (!feof( cfptr ) ) { 19 printf( "%-10d%-13s%7.2f\n", account, name, balance 20 ); fscanf( cfptr, "%d%s%lf", &account, name, &balance ); 21 } 22 23 fclose( cfptr ); 24 } 25 26 return 0; 27 } Account Name Balance 100 Jones 24.98 200 Doe 345.67 300 White 0.00 400 Stone -42.16 500 Rich 224.62

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 12

Unformatted File I/O 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 13

1 /* Fig. 11.11: fig11_11.c 2 Creating a randomly accessed file sequentially */ 3 #include <stdio.h> 4 5 struct clientdata { 6 int acctnum; 7 char lastname[ 15 ]; 8 char firstname[ 10 ]; 9 double balance; 10 }; 11 12 int main() 13 { 14 int i; 15 struct clientdata blankclient = { 0, "", "", 0.0 }; 16 FILE *cfptr; 17 18 if ( ( cfptr = fopen( "credit.dat", "w" ) ) == NULL ) 19 printf( "File could not be opened.\n" ); 20 else { 21 22 for ( i = 1; i <= 100; i++ ) 23 fwrite( &blankclient, 24 sizeof( struct clientdata ), 1, cfptr ); 25 26 fclose( cfptr ); 27 } 28 29 return 0; 30 } 14

Random Access fseek 15 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

Unformatted File Read 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 16

Using Command-Line Arguments Pass arguments to main on DOS or UNIX Define main as int main( int argc, char *argv[] ) intargc 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.c 2 Using command-line arguments Notice */ argc and 3 #include <stdio.h> argv[] in main 4 5 int main( int argc, char *argv[] ) 6 { 7 FILE *infileptr, *outfileptr; 8 int c; argv[1] is the second 9 10 if ( argc!= 3 ) argument, and is being read. 11 printf( "Usage: copy infile outfile\n" ); argv[2] is the third 12 else argument, and is being 13 if ( ( infileptr = fopen( argv[ 1 ], "r" ) )!= written to. NULL 14 ) 15 if ( ( outfileptr = fopen( argv[ 2 ], "w" ) )!= 16 NULL ) 17 while ( ( c = fgetc( infileptr ) )!= EOF )18 fputc( c, outfileptr ); 19 20 else 21 printf( "File \"%s\" could not be opened\n", 22 argv[ 2 ] ); outfileptr. 23 else 24 printf( "File \"%s\" could not be opened\n", argv[ 1 ] ); 25 26 return 0; 27} Loop until End Of File. fgetc a character from infileptr and fputc it into

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

int a; unsigned long b; Implicit Casting Example float f, g; double d; g = a + f; // a transforms to float d = 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- Keyword static File Programs 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