No Objects, No Type Safety

Slides:



Advertisements
Similar presentations
A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
Advertisements

Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 6P. 1Winter Quarter I/O in C Lecture 6.
Console and File I/O - Basics Rudra Dutta CSC Spring 2007, Section 001.
V-1 University of Washington Computer Programming I File Input/Output © 2000 UW CSE.
 2007 Pearson Education, Inc. All rights reserved C Formatted Input/Output.
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
CMPE13 Cyrus Bazeghi Chapter 18 I/O in C. CMPE Standard C Library I/O commands are not included as part of the C language. Instead, they are part.
Chapter 9 Formatted Input/Output. Objectives In this chapter, you will learn: –To understand input and output streams. –To be able to use all print formatting.
Lone Leth Thomsen Input / Output and Files. April 2006Basis-C-8/LL2 sprintf() and sscanf() The functions sprintf() and sscanf() are string versions of.
CP104 Introduction to Programming File I/O Lecture 33 __ 1 File Input/Output Text file and binary files File Input/output File input / output functions.
Constants Numeric Constants Integer Constants Floating Point Constants Character Constants Expressions Arithmetic Operators Assignment Operators Relational.
Chapter 18 I/O in C.
File Handling In C By - AJAY SHARMA. We will learn about- FFile/Stream TText vs Binary Files FFILE Structure DDisk I/O function OOperations.
Characters and Strings File Processing Exercise C Programming:Part 3.
File IO and command line input CSE 2451 Rong Shi.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Chapter 11: Data Files and File Processing Files and streams Creating a sequential access file Reading data from a sequential access file Using fgetc()
Basic I/O in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Stream Model of I/O header file: A stream provides a connection.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Introduce some standard library functions.
Copyright © Curt Hill Formatting Reals Outputs other than normal.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Input and Output.
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
Operating System Discussion Section. The Basics of C Reference: Lecture note 2 and 3 notes.html.
1 CSC103: Introduction to Computer and Programming Lecture No 28.
CS 1704 Introduction to Data Structures and Software Engineering.
Files A collection of related data treated as a unit. Two types Text
FILES IN C. File Operations  Creation of a new file  Opening an existing file  Reading from a file  Writing to a file  Moving to a specific location.
Files. FILE * u In C, we use a FILE * data type to access files. u FILE * is defined in /usr/include/stdio.h u An example: #include int main() { FILE.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
Real Numbers Device driver process within the operating system that interacts with I/O controller logical record 1 logical record 2 logical record 3.
C Formatted Input/Output
User-Written Functions
Chapter 7 Text Input/Output Objectives
Chapter 22 – part a Stream refer to any source of input or any destination for output. Many small programs, obtain all their input from one stream usually.
Input/output.
TMF1414 Introduction to Programming
University of Washington Computer Programming I
Chapter 7 Text Input/Output Objectives
EKT120: Computer Programming
File Access (7.5) CSE 2031 Fall July 2018.
An Introduction to C Programming
Chapter 18 I/O in C.
Introduction to Computer Programming Lecture 18 Binary Files
File I/O.
Introduction to C CSE 2031 Fall /3/ :33 AM.
C Programming:Part 3 Characters and Strings File Processing Exercise.
Arrays in C.
CS111 Computer Programming
File Input/Output.
Programming in C Input / Output.
What you need for the 1st phase of project
Programming in C Input / Output.
Files I/O, Streams, I/O Redirection, Reading with fscanf
Lecture 13 Input/Output Files.
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Beginning C Lecture 11 Lecturer: Dr. Zhao Qinpei
A First Book of ANSI C Fourth Edition
Chapter 18 I/O in C.
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Text and Binary File Processing
File Input and Output.
File Handling.
Fundamental of Programming (C)
Programming in C Input / Output.
Module 12 Input and Output
Introduction to C EECS May 2019.
Professor Jodi Neely-Ritz University of Florida
Professor Jodi Neely-Ritz University of Florida
Chapter 18 I/O in C.
Presentation transcript:

No Objects, No Type Safety C Style Files No Objects, No Type Safety Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Introduction Files are library based items All about functions and pointers Not much new syntax Still plenty to learn Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Slippery Files are rather slippery compared to most data types in C ints, doubles and chars are machine constructs They have a very machine dependent look They have hardware operations that manipulate Files on the other hand are operating system constructs They are means for connecting programs (in memory) to disk (or other files) data Different operating systems running on the same machine will have different means of accessing their files, though their integers will be the same Furthermore they are usually not copyable since they have pointers pointing at them Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Standard files C provides us with three standard files that require no declaration or preprocessing stdin, stdout, stderr The standard files are streams of characters with newline characters interspersed and are terminated by an EOF mark The EOF mark can be handled in a variety of ways: A character Disk directory entry has a length Some other ways are possible as well Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Standard I/O There are two standard functions that do console I/O The function printf does output on the standard output file The function scanf does input on the standard input file We do not open or close them or declare them in any way The include is <stdio.h> Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill printf May have one or more arguments First is a string Constant in double quotes or variable The string may contain format descriptors All subsequent parameters are values that are to be part of the message of the quoted string There is a matching of the subsequent arguments with the %x format descriptors in the string The format descriptor tells how to display the value in question Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Example Suppose the following: int x=1,y=-50; printf(“X is %d and Y is %d\n”,x,y); The result on output is: X is 1 and Y is -50 Format descriptors start with a % The second and subsequent parameters are matched into the string These are all value parameters Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Notes scanf will use a similar scheme but takes a pointer towards its parameters This is usually done using address-of operator (&) Since printf does not use the & all of its parameters are passed by value, which means we could use expressions printf("The sum is %f\n",a+b); is fine Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Format Descriptors Some common format descriptors that we could use are: %d - Handle this as an integer and display the value %f - Handle this as a float and display the value %c - Handle this as a character and display the value There are many others as well as modifiers Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Type Checking ANSI C does not check that the format descriptor and the parameter match in type Any cells in memory can contain (and thus be interpreted) as an integer, a character or a floating point number If you mismatch a format descriptor and a variable (or expression) it will treat the memory as if it were the noted type The way we store an integer and the way we store a real is quite different Net result garbage output Copyright © 2007-2016 – Curt Hill

Type Checking Continued Certain mismatched combinations are not a problem On some machines a double and float are essentially the same until you exceed the precision of float The Pentium is not one of these Depending on alignment, char can be displayed as an integer or character Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Lengths Between the % and the format descriptor can come a length For integers using %d %d means leave no extra blanks %4d means use at least 4 spaces Any spaces will come at the front If item needs more than 4 it will use it Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Floats For floats using %f %f means standard default A constant may also be inserted %12f This may also include a decimal %12.5f means: Entire width is 12 Digits after decimal of 5 The digit comes out of the 12 If more are needed the 12 can be enlarged This is fixed decimal format Exponential format is with the %e Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Modifiers A modifier l can be used in front of the f or d to indicate long An f modifier is for float a lf for long float (ie double) The l comes after the length => %12.8lf Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Issues Since the second and subsequent parameters have no type, type mismatches can occur: int i; printf(“%f”,i); Gives no compile errors The number may disagree: printf(“Answer:”,i); Prints no variable value printf(“%d %d”,i); Is not so great either Length errors may also occur double d; printf(“Answers: %f, %d”,d,i); Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill scanf Converts strings of input symbols into variables The string has only blank separated directives The input determines length etc. so only simple directives are needed The second and subsequent parameters are all pointers Do not forget the & (address of) operator Example: int i; double d; scanf(“%d %lf”,&i,&d); Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Why? We are well past console I/O, but this scheme also works on files There is an abundance of code that uses these functions and their relatives They all still work in C++, even though designed for C Next using disk files Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Normal file usage A file has to be declared Files are pointers to control structures Inside stdio is a structure type called FILE We don't need to know the internal contents of this FILE structure since that changes from OS to OS What we do need to know is the functions that use a FILE * pointer Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Declaration We do not actually get a FILE struct but a pointer to a FILE Example: FILE * infile, *outfile; The structure itself will almost always be owned by the OS which is why we declare it as a pointer The pointer can be copied but not the structure Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Open The function fopen will open the file When we open the file we need to specify a couple of things: Direction of transfer input or output External file to connect to These become parameters to fopen Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Example: FILE * infile; ... infile = fopen("input.dat","r"); Three things to notice: fopen returns a pointer to a file Specify the file name Specify the direction Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Returning a pointer The fopen returns a pointer It does not take one as a parameter All the other functions will do that If there is an error it returns the NULL pointer Test as follows: if(infile) // then ok Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Connection We have to specify what external file to connect with First parameter is a string Does not have to be a constant File name can be obtained from command line or read from input file It may contain directory information such as disk or subdirectory MS: \ must be doubled when constant Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Direction We must specify the direction Second parameter Must be string: "r" input "w" output "a" append Some OSs distinguish between text files and binary files (such as how to detect EOF) In these a "b" must be appended to direction for binary: "wb" "rb" "ab" fopen must complete before any other file action Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill File functions Most of our file functions are very similar to what we already have seen, except they have an additional parameter, the file pointer The file pointer is first or last Lack of consistency is annoying fprintf(outfile,string,...) fscanf(infile,string,...) fgets(string,int,file) fgetc(infile) Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill fgets Get a string fgets(string,int,file) The middle integer is the maximum number of characters minus 1 to read Must be room for \0 This one does not strip the \n but does append a \0 Copyright © 2007-2016 – Curt Hill

File functions and standard files The three standard files are somewhat declared: FILE *stdin, *stdout, *stderr; The fopen has already been done Many of our normal functions are just equivalences to new functions with stdin/out/err supplied Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill fgetc Obtains one character from a file It is transformed by a macro to getchar For example getchar calls like: ch = getchar(); A macro transformed into ch = getc(stdin); The macrofollows: #define getchar() getc(stdin) Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Closing int fclose(FILE *) Returns an zero if OK Returns EOF if any errors Frees system allocated buffers Does not change the file pointer Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Other functions int remove (const char * filename); Deletes file, returns 0 if successful int rename(const char * oldname, const char * newname); Renames the file Could also move the file The file name may include directory information Neither of these should be done if the file is open and/or being used Returns zero on success Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill String functions int sscanf(char *s, const char * format, ...) Similar to a scanf except this is not a file operation The string s is the source, not a file int sprintf(char *s, const char * format, ...) Similar to a printf except this is not a file operation The string s is the target of the output, not a file Copyright © 2007-2016 – Curt Hill

Saltine Cracker Theory Text files violate some of the rules of the Saltine Cracker theory Scanf reads in an unpredictable number of chars Then it converts them into an int or double Copyright © 2007-2016 – Curt Hill

Conversion and Text Files Conversion takes time and sometimes space Only needed for files that are to be read by people A file that is to be written by a program and read by another does not need this conversion To avoid the conversion requires the idea of binary files and two new functions fread and fwrite and the sizeof operator Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill sizeof sizeof is not a function but a unary operator It yields an integer (almost) which is the number of bytes needed to store the item Actually returns a size_t item In Borland this is an unsigned int Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Usage There are two ways to use: sizeof expression sizeof (type) The expression is not evaluated, only the type is computed It may be an array or struct, as well as any user defined type or expression If you are in the function that declares an array you get the length of the total array If you are in a function that gets the array passed to it you get the length of a pointer Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Notes sizeof returns the number of bytes needed to store the item Precedence is the same as ! or the prefix ++ Cannot be applied to functions Is a compile time value, not a runtime value We will need this to figure out how many bytes to read or write using fread/fwrite Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Binary files Same declaration as text files: FILE * bfile; Same fopen except that a “b” is appended to the direction What is different is that we do not use fscanf or fprintf No formatting is done, each item occupies memory size without any conversion Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill fwrite Is a function that writes an amount of data to a file without conversion It is not type sensitive it can write any type Requires four arguments: The thing to be written The length of an item The number of items to write (total written is product of these two) The file to write it on Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill fwrite It requires a file pointer that is a binary file, open for output The prototype is: size_t fwrite ( const void * item, int length, int nobj, FILE * stream) Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Notes What do these do? item is a pointer at a single thing to be written or an array of such things It is a constant array Passed by address length is the sizeof one item (int, struct or whatever) nobj is the number of these items to write nobj*length is the number of bytes to write Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Return value The return type is the number of items that were actually written If it is less than nobj then an error must have occurred Now we consider an example Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Example Example for writing ints int ar[100],i; FILE * f = fopen (“ints.f”,”wb”); ... i = fwrite(ar, sizeof(int), 10,f); if(i<10) printf(“error”) Copyright © 2007-2016 – Curt Hill

Example for writings structs struct person{ ... } person_type; person_type employees[500]; int p_count,c; FILE * pfile = fopen(“employees.db”,”wb”); if(pfile!=NULL) { ... c = fwrite(employees, sizeof (person_type), p_count, pfile); c = fwrite(&employees[2], sizeof (person_type), 10, pfile); Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill fread is similar Prototype int fread ( void * ptr, size_t size, size_t nobj, FILE * stream); Copyright © 2007-2016 – Curt Hill

Copyright © 2007-2016 – Curt Hill Conclusion The text file things are duplicated in the iostream library For the C++ type the binary files are most important However, there is plenty of old code that you should be able to read Copyright © 2007-2016 – Curt Hill