Follow
Publications: 120 | Followers: 1

CS1313 Pointer Lesson 1

Publish on Category: Birds 0

File I/O Lesson Outline
File I/O Lesson OutlineFile I/O Using Redirection #1File I/O Using Redirection #2Direct File I/O #1Direct File I/O #2File I/O ModeFILEPointerReading from a FileWriting to a Filescanfvsfscanf/printfvsfprintffcloseHow to Use FileI/O
Special File PointersstderrBufferingI/OBuffering is Good!Buffering is Bad!Whystderris GoodUsingstderr
File I/O LessonCS1313 Fall 2018
1
File I/O LessonCS1313 Fall 2018
2
File I/O Using Redirection #1
So far in C, we’ve been using only standard input (keyboard) and standard output (monitor).Weknow that we can input from a file by redirectingthe file into standard input:%big_statistics<actual_1.txtLikewise, we can output to a file byredirecting standard output into a file:%big_statistics>actual_1_output.txt
File I/O LessonCS1313 Fall 2018
3
File I/O Using Redirection #2
In fact, we can combine redirected inputwithredirected output:%big_statistics<actual_1.txt \> actual_1_output.txtBut what if we wanted to use multiple filesat the sametime?For example, suppose we wanted to runaweather forecast, and we had a file containingourinitial conditions(for example,the observed weather at midnight) and a different file containing data describing the terrain of the continental US.We want to use both of these files. But how?
File I/O LessonCS1313 Fall 2018
4
Direct File I/O #1
Most programming languages support reading and writing files directly from within the program, without having to use redirecting.In C, we canopena file using thefopenfunction:...char filename[filename_length+1];FILE*fileptr= (FILE*)NULL;...strcpy(filename, "actual_1.txt");fileptr=fopen(filename, "r");...What does this mean?
File I/O LessonCS1313 Fall 2018
5
Direct File I/O #2
...char filename[filename_length+1];FILE*fileptr= (FILE*)NULL;...strcpy(filename,"actual_1.txt");fileptr=fopen(filename, "r");...Thefopenfunction opens a file in preparation for reading, writing or appending to a file.The first argument is a string representing the filename.The second argument is a string that encodes theI/O mode.
File I/O LessonCS1313 Fall 2018
6
File I/O Mode
...char filename[filename_length+1];FILE*fileptr= (FILE*)NULL;...strcpy(filename,"actual_1.txt");fileptr=fopen(filename, "r");...The second argument is a string that encodes the I/O mode, which can be:"r"– Open the file for reading."w"– Open the file for writing."a"– Open the file for appending (writing at the end of an existing file).
File I/O LessonCS1313 Fall 2018
7
FILEPointer
...char filename[filename_length+1];FILE*fileptr= (FILE*)NULL;...strcpy(filename,"actual_1.txt");fileptr=fopen(filename, "r");...The functionfopenreturns afile pointer, which is a pointer to a special data type that’s used to identify and describe a file.If for some reason the file can’t be opened,thenthereturnvalue offopenisNULL.
File I/O LessonCS1313 Fall 2018
8
Reading from a File
In C, we can read from a file using the functionfscanf, which is exactly likescanfexceptthat its first argument is a file pointer:fscanf(fileptr, "%d", &number_of_elements);
File I/O LessonCS1313 Fall 2018
9
Writing to a File
In C, we can write to a file using the functionfprintf, which is exactly likeprintfexceptthat its first argument is a file pointer:fprintf(fileptr,"The number of elements is %d.\n",number_of_elements);
File I/O LessonCS1313 Fall 2018
10
scanfvsfscanf/printfvsfprintf
What’s the difference betweenscanfandfscanf, or betweenprintfandfprintf?Well,scanfreads fromstdinonly, whilefscanfcan read from any file.Likewise,printfwrites tostdoutonly, whilefprintfcan write to any file.In fact, some implementations of C definescanf(...)asfscanf(stdin, ...), andprintf(...)asfprintf(stdout, ...).
File I/O LessonCS1313 Fall 2018
11
fclose
TheC standard library also has a function namedfclosethat takes a file pointerargument.Itcloses the appropriate file and returns 0 if the file closed properly, or an error code otherwise:constintfile_close_success= 0;intfile_close_status;...file_close_status=fclose(fileptr);if (file_close_status!=file_close_success) {printf("ERROR:couldn'tclose thefile %s.\n",filename);exit(program_failure_code);} /* if (file_close_status!=file_close_success) */
File I/O LessonCS1313 Fall 2018
12
How to Use FileI/O
...FILE*fileptr= (FILE*)NULL;...fileptr=fopen(filename, "r");if (fileptr== (FILE*)NULL) {printf("ERROR:can'topen file %s to read.\n",filename);exit(program_failure_code);} /* iffileptr== (FILE*)NULL) */fscanf(fileptr, "%d", &number_of_elements);for (element =first_element;element <number_of_elements; element++) {fscanf(fileptr, "%f%f",&input_variable1[element],&input_variable2[element]);} /* for element */if (fclose(fileptr) !=file_close_success) {printf("ERROR:can'tclose file %s after reading.\n",filename);exit(program_failure_code);} /* if (fclose(fileptr) !=file_close_success) */...
Special File Pointers
In C, there are three special file pointers that exist all the time, two of which are already old friends:stdin,stdoutandstderr.We already know this:scanf(…);means exactly the same asscanf(stdin,…);printf(…);means exactly the same asfprintf(stdout,…);But what aboutstderr?
File I/O LessonCS1313 Fall 2018
13
stderr
It turns out thatstderris used exactly likestdout, except that you have to usefprintfto usestderr:fprintf(stderr,…);There’s no equivalent ofprintfforstderr.Where doesstderrgo? To the terminal screen, just likestdout.Okay, but then why do we needstderrat all, if it behaves exactly likestdout, except less convenient to use??
File I/O LessonCS1313 Fall 2018
14
Buffering I/O
When you output to a file, there are two options:Unbuffered output: The bytes that you output go directly into the file you’re outputting to.Buffered output: The bytes that you output wait in a special array in RAM until there are enough bytes to justify spinning the disk drive.Buffer: An array where data is temporarily held, typically until a specific event occurs.
File I/O LessonCS1313 Fall 2018
15
Buffering is Good!
Whenyou havejustalittlebitofoutput,it doesn’t matter whether you do buffered or unbuffered.Whenyou havea lot ofoutput,buffered is much faster than unbuffered,becauseyou spin the diskdrive lessoften.Unbuffered: Spin the disk every timefprintfis called.Buffered: Spin the disk only when the buffer is full.So, we should always buffer, right?
File I/O LessonCS1313 Fall 2018
16
Buffering is Bad!
What if your program crashes while there’s data in the output buffer that hasn’t gotten to disk yet?Lost forever and never recoverable!If you don’t know what your output should look like, then you might not even notice that you’ve lost data (which might be important data).So what’s the most important data tonotbuffer?ERROR MESSAGES!Therefore, error messages should be output unbuffered, so that they go out before the program crashes.
File I/O LessonCS1313 Fall 2018
17
WhystderrIs Good
stdout: bufferedstderr: unbufferedAll other files: buffered by default, unless you explicitly set them to be unbuffered.
File I/O LessonCS1313 Fall 2018
18
Usingstderr
if (number_of_sad_clowns<minimum_number_of_clowns) {fprintf(stderr,"ERROR: you can’t have a negative");fprintf(stderr,"number of sad clowns!\n");exit(program_failure_code);} /* if (number_of_sad_clowns< ...)*/
File I/O LessonCS1313 Fall 2018
19

0

Embed

Share

Upload

Make amazing presentation for free
CS1313 Pointer Lesson 1