Sie sind auf Seite 1von 34

COP-2220C

Instructor: Brian Williamson

“640K ought to be enough for anybody.” –Bill Gates, 1981


Terms to Know
 File – Data stored onto non-volatile memory, such as a
hard drive.
 Buffer – Area of memory used for temporary data
storage.
 Stream – A sequence of objects (such as bytes,
characters).
 Appending – When you begin at the ending of a previous
data stream.
 EOF – The end of file character.
Files and C
 You know files as data saved on a hard drive.
 For a lot of programs you will want to access the files for
reading and/or writing.
 Read in large amounts of data for processing.
 Output calculations into a log file.
 Although on a disk, C treats the file as though it was in
memory.
 It is like a large block of data in memory.
 Comes with a pointer to this memory.
 In reality it swaps data in and out of a buffer.
Files and pointers
 When reading from a file data is read into a buffer in
RAM that you have a pointer to.
 When writing to a file, data is held into the buffer
before writing to the hard drive (a slow process).
 The "file position" automatically moves along as you
read and write.
 The end of the file is marked by a special character
inserted by the O/S – the EOF character
File position

EOF
File Buffer Data Flow

DISK MEMORY

File Buffer

File Pointer

Fortunately, thanks to the functions C provides, you don’t have to


deal with this.
Types of Files
 Text files are a sequence of bytes on a disk that can be
represented as ASCII characters.
 Almost like a very long string.
 May contain escape characters \n \r \t
 May contain an end of file marker (numeric 0x1a)
 Binary files are a sequence of bytes on a disk that
represent raw data.
 If you output a double into a file, it will be saved as the 8
bytes that the double contained.
 May be easier to output your data to a binary file as it does
not have to be formatted.
stdio.h
 We have been using stdio.h for printf and scanf.
 Also contain everything needed for file IO.
 FILE * is a new data type.
 Is the pointer to the file’s stream of data.
 FILE * fopen(char *fileName, char *mode)
 Opens the file specified by the string fileName and in the mode
specified in the string mode.
 Mode may be “w” for write, “r” for read, “a” for append.
 Can be combined “rw” for read/write.
 May inclue “b” for binary file.
 fileName can be a location on the disk.
 Returns a pointer to the file that was open.
 int fclose(FILE *file)
 Closes the file specified in the pointer, returns 0 if successful.
File Example
FILE *inputFile; // represents a connection to a file

inputFile = fopen("c:\\mytextfile.txt", "wb");


fclose(inputFile);

 When you read a file “r” it must exist.


 Writing to a file “w” will create the file when it is opened.
fopen modes

Text Files Binary Files


r Reading rb

w Writing (create file) wb

a Appending(create file) ab

r+ Read and Write – from beginning rb+

w+ Read and Write – truncate wb+


a+ Read and Write - append ab+
I/O for text files
 fprintf and fscanf
 Work exactly as printf and scanf except…
 You include the file pointer as your first parameter.
 printf(“Hello world!\n”);
 fprintf(myFile, “Hello World!\n”);
 scanf(“%i”,&x);
 fscanf(myFile, “%i”,&x);
 fscanf is pretty terrible for reading from a file if you do
not know the exact format.
Better I/O for text files
 int fgetc(FILE *ptr)
 Returns the next character from a file.
 int fputc(int character, FILE *ptr)
 Puts a character to a file. Returns the character written if succesful.
 int fgets(char *str, int num, FILE *ptr)
 Pulls the next line from the file into str and appends a ‘\0’ onto str.
 Reads characters and copies them up until the next ‘\n’ is seen.
 int fputs(const char *str, FILE *ptr)
 Writes the string to a file.
 int feof(FILE *ptr)
 Returns a 0 if not at the end of the file.
 Returns a non-zero value if at the end of the file.
Writing and reading example
FILE *inputFile; // represents a connection to a file
char buffer[1000];

inputFile = fopen("mytextfile.txt", "w");


fputs("Hello world!\n", inputFile);
fputs("How are you?\n", inputFile);
fputs("Ok bye!\n", inputFile);
fclose(inputFile);

inputFile = fopen("mytextfile.txt", "r");


while (!feof(inputFile))
{
fgets(buffer, 1000, inputFile);
printf("%s", buffer);
}
fclose(inputFile);
File buffer
 When you read and write from a file it is stored in a file
buffer that the program maintains.
 This is for efficiency as reading/writing to a hard drive is
time consuming.
 Data to be read or written is saved in the buffer and sent
out in a large block.
 You can control this buffer with the fflush(FILE *)
function.
 Flushes whatever is in the buffer so everything is written
out to the file and read back in.
 May be useful for debugging.
Binary File I/O
 int fread(void *ptr, int size, int count, FILE *stream)
 Reads in “count” number of elements that are “size” bytes
from FILE stream to pointer ptr.
 Returns the number of raw bytes read.
 int fwrite(void *ptr, int size, int count, FILE *stream)
 Write out count number of elements that are “size” bytes
from pointer ptr to FILE stream.
 Returns the number of raw bytes written.
 These functions read and write raw data from memory to
the file.
Binary I/O Example
FILE *fp;
Fp = fopen("myFile", "wb");
double d = 27.5;
fwrite(&d, sizeof(double), 1, fp); // writes 8 bytes

long int myArray[5] = { 10, 20, 30, 40, 50 };


fwrite(myArray, sizeof(long int), 5, fp);

Date birthday = { 11, 16, 1980 };


fwrite(&birthday, sizeof(Date), 1, fp);
fclose(fp);

d = 0;
Date input;
long int inputArray[5];
fp = fopen("myFile", "rb");
fread(&d, sizeof(double), 1, fp);
fread(inputArray, sizeof(int), 5, fp);
fread(&input, sizeof(Date), 1, fp);
printf("%lf", d); //Output 27.5
Moving File Position
 When you open a file you read from the beginning to the
end.
 It is possible, however, to move the file pointer as
needed.
 fseek – move to a specified location, relative to the
beginning, end, or current position in the file
 fgetpos – stores the current file position
 fsetpos – returns to a previously stored file position
 ftell – returns the current file position as a long int
 rewind – put the file position at 0 (zero)
Learning File Types
 You may read standards on how a file is stored.
 .rgb may be binary, but is a simple RGB format for every
pixel.
 .csv is a text file with commas separating values in the row
of a table.
 Very useful for handling large amounts of data for analysis.
 Excel can read in and output .csv files.
 You may also create your own file type.
 Follows your rules for outputting binary or separating out
text.
Concepts Summary
 Files can be thought of as a sequence of bytes on an external
storage medium
 Files can be text or binary
 Reading text files can be complicated. Read the descriptions of the
format specifiers carefully. Don't guess! Incorrect format specifiers
will do something, and might appear to work, but the behavior is
really indeterminate.
 It is impossible to read a binary file without knowing what the bytes
represent – the data types and their locations in the file.
 Binary files can be read and written with large blocks of data or a
byte at a time using fread and fwrite
 You can mix binary and text file access, but it shouldn't be done.
The behavior is indeterminate, and tends to result in guessing what
the code will do, and then changing it – over and over.
Reading/Writing Text File
 Open a file for text writing. Put all of the text in the file
that appears on this slide. Close the file.

 Open the file for reading. Read the file one character at a
time, counting how many of each vowel occur in the text.

 Close the file, and then open it for reading, this time
counting how many words are in the file.

 Output the results.


Reading/Writing a Binary File
 Open a file for binary writing.

 Generate 1000 random integers between 1 and 100 inclusive, writing them
into the file as they are generated.

 Close the file, and then open it for reading.

 Read in all the values, and calculate their sum as they are read. (no arrays
needed) Find and output the average of the numbers.

 Repeat the exercise above using an array. Read all the values from the file
in one statement.

 Just for fun... If you seed the random number generator with the value
123, use fseek to read the 30th number in the file. What is it?
Cipher Example
 A cipher is a way of writing a coded message
 The simplest form is a substitution cipher
 Substitute one character for another:
 Every a is changed to z
 Every b is changed to y
 Etc…
 Our goal: Read a file that explains the cipher
 Create a struct that holds the original character and the cipher
character
 Read the cipher file line by line filling out the struct
 Cipher array is of size 52
Concepts Summary
 Don't mix the use of functions intended for Text and
Binary files.
 Keep a reference for the description of the format
specifiers handy!
 Close the files as soon as you are done with them.
 Draw pictures of a binary file – use graph paper to help
keep track of the bytes.

 Don't guess! It will take forever to work with files using


trial and error, and the result might not be doing exactly
what you expect it to be doing.
Homework Assignment 9
 As you could guess, we are going to finish the cipher
example.
 We read in the cipher which is important, now it needs to
be applied:
 On BlackBoard attached to this assignment there is a
encryptedText.txt file
 If you open it, it will make no sense
 The cipher is easy, but takes too long to apply by hand.
 Let’s make a program that reads in a cipher input and
produces a translated output
Homework Assignment 9
 The program’s overall structure is this:
 Open two files, one for input “r” and one for output “w”
 Read a line from the input file into an input string
 Go through character from the input string and put its
cipher substitution equivalent into an output string
 Output the string to the output file
 When finished, the output file should be a readable
famous paper
Homework Assignment 9
 Good news though! I have provided a template that explains
thoroughly what to do
 What you need to do:
 1) Download encryptedText.txt to your project directory (or a location
you can easily access)
 2) Download cipher.txt which contains the actual cipher substitution
 3) Download “Homework 9 Template.c”
 4) Go through the template and fill in all the TODO: comments
 Alternatively you can use the template as guidelines and attempt to
write your own solution to this problem.
 Some of you may find this easier
 More good news: You will have two weeks to finish this.
 Don’t wait until the last moment.
 Start early, ask questions, continue.
Exam 3 Coming Up
 Will test what we have learned in Module 3:
 Structs
 Creating structs, . Operator, -> operator
 Arrays and pointers
 [] calculating memory addresses, effective size, parallel arrays
 Dynamic memory allocation
 Stack vs Heap, uses of dynamic allocation
 File I/O
 File buffers, disk I/O
Exam 3 Study Tips
 Will be a similar design to previous exams:
 23 multiple choice, 2 problem solving assignments.
 Distribution of terms, concepts, code reading, problem
solving is the same.
 LOTS of functions learned in Module 3.
 Memorize the name of the function and its uses (especially
what it returns if anything).
 You can also memorize the parameters, but you can
probably infer them from the code.
Exam 3 Functions to Study
 strcpy – Copy a string
 strlen – Find the length of a string
 strcmp – Compare two strings
 strstr – Find a string within a string
 malloc – Allocate dynamic memory
 calloc – Allocate array of dynamic memory
 realloc – Change the size of dynamically allocated memory
 free – Release dynamically allocated memory
 memcpy – Copy bytes of memory
 memset – Set bytes of memory
Exam 3 Functions to Study
 fopen – Open a file
 fread – Read bytes from a file
 fwrite – Write bytes to a file
 fputs – Write a string to a file
 fgets - Read a string from a file
 fscanf – scanf for files
 fprintf – printf for file
 fgetc – Read a single character from a file
 fputc – Write a single character to a file
 feof – Determine if at the end of the file
 fflush – Flush the file buffer
Exam 3 Study Tips
 Study terms, functions, concepts.
 Study homework assignments and in class activities.
 Strongly recommend starting on homework 9.
 This homework makes use of structs and file I/O.
 Ask questions if you do not understand a concept or how
a particular function works.

Das könnte Ihnen auch gefallen