Presentation is loading. Please wait.

Presentation is loading. Please wait.

No Objects, No Type Safety

Similar presentations


Presentation on theme: "No Objects, No Type Safety"— Presentation transcript:

1 No Objects, No Type Safety
C Style Files No Objects, No Type Safety Copyright © – Curt Hill

2 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 © – Curt Hill

3 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 © – Curt Hill

4 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 © – Curt Hill

5 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 © – Curt Hill

6 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 © – Curt Hill

7 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 © – Curt Hill

8 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 © – Curt Hill

9 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 © – Curt Hill

10 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 © – Curt Hill

11 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 © – Curt Hill

12 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 © – Curt Hill

13 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 © – Curt Hill

14 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 © – Curt Hill

15 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 © – Curt Hill

16 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 © – Curt Hill

17 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 © – Curt Hill

18 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 © – Curt Hill

19 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 © – Curt Hill

20 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 © – Curt Hill

21 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 © – Curt Hill

22 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 © – Curt Hill

23 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 © – Curt Hill

24 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 © – Curt Hill

25 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 © – Curt Hill

26 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 © – Curt Hill

27 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 © – Curt Hill

28 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 © – Curt Hill

29 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 © – Curt Hill

30 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 © – Curt Hill

31 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 © – Curt Hill

32 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 © – Curt Hill

33 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 © – Curt Hill

34 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 © – Curt Hill

35 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 © – Curt Hill

36 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 © – Curt Hill

37 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 © – Curt Hill

38 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 © – Curt Hill

39 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 © – Curt Hill

40 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 © – Curt Hill

41 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 © – Curt Hill

42 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 © – Curt Hill

43 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 © – Curt Hill

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

45 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 © – Curt Hill


Download ppt "No Objects, No Type Safety"

Similar presentations


Ads by Google