Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

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

2 Overview C Functions to Open and Close Streams Declaring, Opening, and Closing Files Reading and Writing Files Example

3 Sharing Data Imagine 5 people around the world at terminals playing DOOM!  Central Game server Tracks games in session. Keeps record of players and status  How could we make our programs communicate?  Clearly, writing data, and reading data files is a possible solution!

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

5 Opening a File Files must be opened before they are worked with To open a file is to establish a link b/t your program, the OS, and the file An “open file” is one with which your program can communicate Analogous to taking the phone off the hook Helps preserve file integrity FILE represents a “stream”

6 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() //prototype FILE *fopen(char* FileName, char *Mode); FILE *fp; fp = fopen(“proj01.c”, “r”);

7 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”);

8 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”);

9 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”);

10 pgm 11.1 from Bronson textbook #include 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; }

11 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”);

12 pgm 11.2 – Writing a File example #include 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

13 Note File Size

14 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”);

15 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()

16 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

17 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

18 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!

19 Writing a File How many characters are stored in prices.dat? How does this differ from the number mentioned in your textbook? Using a debugger, you can do a “dump” of prices.dat 51 characters can be found in prices.dat fclose() did not place a special end-of-file marker in the last item in the file B Smith: hidden B Smith: hidden

20 EOF EOF is not a special character that you retain in a variable It’s a constant (system dependent) that’s returned by various functions  scanf(), sscanf(), fscanf(), etc, in the event of an input failue EOF is also a valued returned by  getc(), getchar(), fgetc() in the event of a failure, or if no more characters are available to be read B Smith: move to end? B Smith: move to end?

21 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

22 Reading data from a file #include 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!


Download ppt "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."

Similar presentations


Ads by Google