Top Banner
C File Processing - I Math 130 B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts since most is discussed. Good for handout, bad for lectures. B Smith: 4/13/2005 9:54 AM: Rate: 3, low discussion, implement, “Your turn…” Time: 50 minutes B Smith: Rate:2/4 More examples needed, fewer words. B Smith: Sp06: rate 2.5 Worked mostly from examples 11.1 and 11.2. Need better examples.
18

C File Processing - I Math 130 B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts.

Dec 17, 2015

Download

Documents

Bryan Baker
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: C File Processing - I Math 130 B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts.

C File Processing - I

Math 130

B Smith:

Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts since most is discussed. Good for handout, bad for lectures.

B Smith:

Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts since most is discussed. Good for handout, bad for lectures.

B Smith:

4/13/2005 9:54 AM: Rate: 3, low discussion, implement, “Your turn…” Time: 50 minutes

B Smith:

4/13/2005 9:54 AM: Rate: 3, low discussion, implement, “Your turn…” Time: 50 minutes

B Smith:

Rate:2/4 More examples needed, fewer words.

B Smith:

Rate:2/4 More examples needed, fewer words.

B Smith:

Sp06: rate 2.5 Worked mostly from examples 11.1 and 11.2. Need better examples.

B Smith:

Sp06: rate 2.5 Worked mostly from examples 11.1 and 11.2. Need better examples.

Page 2: C File Processing - I Math 130 B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts.

Overview

• C Functions to Open and Close Streams

• Declaring, Opening, and Closing Files

• Reading and Writing Files

• Example

Page 3: C File Processing - I Math 130 B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts.

Opening a File

• We have been working with programs that have read from the “standard input” (the keyboard) written to the “standard output” (the monitor)

• How can we access a file which is not already “connected” to the program?

• File processing is performed using a FILE structure/data-type. First you must declare an instance of the FILE structure. Examples:

FILE* inFile;FILE* prices;FILE* fp;

FILE* inFile;FILE* prices;FILE* fp;

B Smith:

In C a stream is referred to as a FILE. See attached notes.

B Smith:

In C a stream is referred to as a FILE. See attached notes.

Page 4: C File Processing - I Math 130 B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts.

Opening a File

• Use fopen() to open a file• fopen() takes an external name such as

“proj01.c” as an argument• fopen() returns an internal file name for use in

subsequent reads and writes to the file this “handle” is a file pointer returned from fopen()

//prototypeFILE *fopen(char* FileName, char *Mode);

FILE *fp;

fp = fopen(“proj01.c”, “r”);

Page 5: C File Processing - I Math 130 B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts.

fopen()

• The file pointer returned from fopen() points to a file structure

• A file structure contains file details such as buffer location current character position in the buffer whether the file is being read or written

FILE *fp;

fp = fopen(“proj01.c”, “r”);

Page 6: C File Processing - I Math 130 B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts.

fopen()

• The first argument of fopen is the name of the file, taken as a character string

• The second argument is the “mode,” used to indicate how the file is to be used

FILE *fp;

fp = fopen(“proj01.c”, “r”);

Page 7: C File Processing - I Math 130 B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts.

fopen()

• The files opened by fopen() will generally be read, written, or appended allowed modes reflect this

• mode r: read

• mode w: write

• mode a: append, or add to

file name and mode should be enclosed in double quotes

FILE *fp;

fp = fopen(“proj01.c”, “r”);

Page 8: C File Processing - I Math 130 B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts.

pgm 11.1 from Bronson textbook

#include <stdlib.h>#include <stdio.h>int main(){ FILE *inFile; char fileName[13];

printf("\nEnter a file name: "); gets(fileName);

inFile = fopen(fileName,"r"); /* open the file */

if (inFile == NULL) { printf("\nThe file cannot be opened."); printf("\nPlease check that the file currently exists."); exit(1); /* all open streams are closed */ }

printf("\nThe file has been successfully opened for reading"); return 0;}

Page 9: C File Processing - I Math 130 B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts.

Opening a File for Writing:

• This creates a new file makes the file available for output from the function

opening the file if a file with the same name exists, the old file is

erased

outFile = fopen(“prices.bnd”,”w”);

Page 10: C File Processing - I Math 130 B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts.

pgm 11.2 – Writing a File example

#include <stdlib.h>#include <stdio.h>int main(){ int i; FILE *outFile; /* FILE declaration */ float price[] = {39.95,3.22,1.03}; /* a list of prices */ char *descrip[] = { "Batteries", /* a list of */

"Bulbs", /* descriptions */ "Fuses"};

outFile = fopen("prices.txt","w"); /* open the file */ if (outFile == NULL) { printf("\nFailed to open the file.\n"); exit(1); } for(i = 0; i < 3; ++i) fprintf(outFile,"%-9s %5.2f\n",descrip[i],price[i]);

fclose(outFile); return 0;}

system(“start notepad.exe prices.txt”); //to view file

Page 11: C File Processing - I Math 130 B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts.

Note File Size

Page 12: C File Processing - I Math 130 B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts.

Appending To a File• This makes an existing file available for data to be added to end of

file

• If the file opened for appending does not exist, a new file is created

• This new file is available to receive output from the program

• In append mode, data is written to the end of the file

• NB: in write mode, data is written starting at the beginning

outFile = fopen(“prices.bnd”,”a”);

Page 13: C File Processing - I Math 130 B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts.

Reading from a file

• Open the file and save the returned pointer• inFile = fopen(“sales.dat”,”r”);

• Check for existence of file if (inFile == NULL) ...

• requests to open a nonexistent file will return a NULL address

• Read the data using functions similar to scanf(), gets(), and getchar()

Page 14: C File Processing - I Math 130 B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts.

Bailing Out

• Errors should be communicated back to the OS By convention, this is done with exit(1) or exit(0)

• Errors are also typically reported back to the user

• Conventionally, exit will return a value of 0 for success a nonzero value to indicate failue

• exit calls fclose for each open output file

Page 15: C File Processing - I Math 130 B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts.

Closing a File

• Use fclose() to close the files you’ve opened

• There is a limit to the maximum number of files you can have open

• Use the same internal pointer name to close the file

• Open files are normally closed automatically by the operating system upon exit

Page 16: C File Processing - I Math 130 B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts.

Writing to Files

• These functions are almost identical to those used for displaying to a monitor

fputc(c, filename) Write a single character to a file

fputs(string, filename) Write a string to the file

fprintf(filename, “format”, args) Write the values of the arguments to the file according to the format string

fputc(‘z’, outFile); Write a ‘z’ to the file

fputs(“Nemo was a fish”, outFile) Write the string to the file

fprintf(outFile, “%s %d”, descrip, price)

B Smith:

Not clear here what’s a proto and what’s a function example!

B Smith:

Not clear here what’s a proto and what’s a function example!

Page 17: C File Processing - I Math 130 B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts.

Reading Files• Very similar to reading data from the keyboard

all detect EOF. fgetc() and fscanf() return EOF when the marker is detected fgets() returns a NULL when it detects the end of a file

fgetc(filename) Read a single character from the file

fgets(stringname,n, filename) Read n-1 characters from the file and store in stringname

fscanf(filename, “format”, &args) Read values for the listed arguments

fgetc(infile); // Read the next character from the file

fgets(message, 10, inFile) //Read file until: 9 characters, OR \n, OR EOF

fscanf(inFile, “%f”, &price) //Read a floating point number

Page 18: C File Processing - I Math 130 B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts.

Reading data from a file

#include <stdlib.h>#include <stdio.h>int main(){ char descrip[10]; float price; FILE *inFile;

inFile = fopen("prices.txt","r"); if (inFile == NULL) { printf("\nFailed to open the file.\n"); exit(1); }

while (fscanf(inFile,"%s %f",descrip,&price) != EOF){ printf("%-9s %5.2f\n",descrip,price); } fclose(inFile);

return 0;}

B Smith:

Not a great example since it uses the same field names! The more logical thing to do would be to read a new file with fields chosen by the user!

B Smith:

Not a great example since it uses the same field names! The more logical thing to do would be to read a new file with fields chosen by the user!