lecture18-mar3 - 3/3/10 Announcements - Lecture 18...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
3/3/10 1 Announcements - Lecture 18 • Assignment 4 – Designs due in Friday’s recitation – Q&A • Topics for today (more Ch. 22) – Formatted file IO – Binary file operations – Random access file operations • Non sequential file operations Your SLOC Counter - IPO SLOC Counter How to organize the design of your program into modules that reduce the complexity ??? Name of the file which contains the C program A C language source program (in a text file on disk) Program Functions SLOC Count Report Opening a File - Nuances In Windows, be careful when the file name in a call of fopen includes the \ character. The call fopen("c:\project\test1.dat", "r") will fail, because \t is treated as a character escape. One way to avoid the problem is to use \\ instead of \ : fopen("c:\\project\\test1.dat", "r") An alternative is to use the / character instead of \ : fopen("c:/project/test1.dat", "r") File Buffering • Transferring data to or from a disk drive is a relatively slow operation. • The secret to achieving acceptable performance is buffering. – Data written to a stream is actually stored in a buffer area in memory; when it’s full (or the stream is closed), the buffer is “flushed.” – Input streams can be buffered in a similar way: the buffer contains data from the input device; input is read from this buffer instead of the device itself. • The functions in <stdio.h> perform buffering automatically when it seems advantageous. • On rare occasions, we may need to use the function fflush. File Buffer Flushing • By calling fflush , a program can flush a file’s buffer as often as it wishes. • A call that flushes the buffer for the file associated with fp : fflush(fp); /* flushes buffer for fp */ • A call that flushes all output streams: fflush(NULL); /* flushes all buffers */ • fflush returns zero if it’s successful and EOF if an error occurs. Formatted File IO #include <stdio.h> #include <stdlib.h> #include <string.h> int main( ) { FILE *fp; float ld; int d; char str[80]; char fileName [ ] = “example.txt”; /* open file for output */ fp = fopen(fileName, "w")); if( fp ==NULL ) { printf("Cannot open file.\n"); exit(1); } fclose(fp); /* read back in what was written */ /* open file for input */ fp = fopen(fileName, "r")); if( fp ==NULL ) { printf("Cannot open file.\n"); exit(1);
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 3

lecture18-mar3 - 3/3/10 Announcements - Lecture 18...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online