UCF COP 3502H - Files and Libraries in the C Programming Language

Unformatted text preview:

Files and Libraries in the C Programming LanguageIn order to connect your C program to a file, you need to:ExampleBasic Text File Access A file is a data target or data source that resides on disk and is completelyindependent from your C program. A file on disk exists whether or notyour program is active in memory. It has a name of its own and a locationof its own.In order to connect your C program to a file, you need to:1) declare a file pointer variable in your program2) connect that file variable to the actual disk file with an fopenfunction call3) remember to break the connection when you are finished with thefile by an fclose function call.In between steps 2 and 3, all communication between your program andthe disk file is accomplished by referencing the file pointer variable andnot by using the file’s disk name. The only place the file’s disk name isused is in the fopen function call.The fopen function determines the mode of communication that yourprogram will use in communicating with the file. The file can be openedfor reading ( using “r” mode) or opened for writing ( using “w” mode).Let’s assume that a text file named data.txt resides in the default directoryon your disk drive. You want to open this file for reading (as an inputsource for your program). First, declare a file pointer variable:FILE * infile;Then in your code section, make an appropriate call to the fopen function.infile = fopen(“data.txt”, “r”);If your function call fails for any reason (misspelled name etc) the infilepointer will have the NULL value. If it succeeds, the value will not beNULL. This means that the open call can be placed in an if statementthat checks for failure and notifies the person running your program asfollows:Files in C - 1Files and Libraries in the C Programming LanguageThe above will gracefully terminate your program if the input file is notopened correctly and continue running if it is opened successfully.Assuming it opened correctly, your program can now communicate withthe file by referencing the file pointer infile.ExampleTo read a string variable called name from the file,fscanf(infile, “%s”, name);should work. There are other C functions that can read from a fileopened in read mode. Most are listed in <stdio.h>The use of fscanf is identical to that of scanf except for the new firstargument. The first argument to fscanf must be a file pointer.After you finish processing the file, close it with an appropriate call to thefclose function. The fclose function takes the file pointer as its onlyargument.fclose (infile);Now, suppose you want to open a file named output.txt to receive datafrom your program. Once again, you need a file pointer variable in yourprogram to associate with the file.FILE * outfile;and an appropriate call to the function fopen to make the connection:Files in C - 2if ( NULL == (infile = fopen (“data.txt”, “r”))) {printf(“\nError opening input file\n”);exit(0);}if ( NULL == (outfile = fopen (“output.txt”, “w”))) { printf(“\nError opening output file\n”); exit(0);}It is important to note that this fopen command is potentially destructive.If a file with the same name exists on your disk in the default directory itwill be destroyed by this call.fopen with a request for write mode can fail if there are problems with thedrive such as no more available space (disk is full).Assuming the file opened successfully, the file pointer outfile is not NULLand is your program’s link to the file. You may now write to the file usingthe fprintf function with the file pointer as the first argument. This functionoperates identically to printf but, like fscanf, requires the file pointerargument. fprintf(outfile, “\nThe value of the variable average is %f\n”, average);There are other C functions that can write to a file that has been openedin write mode. Most are listed in <stdio.h>.After you finish processing, be sure to close the output file with a call tofclose.fclose(outfile);This is even more important than closing a file that was opened in readmode. C writes output to buffers and, when it accumulates enough,writes the buffer to disk. If you forget to close an output file, the buffermay not flush and you may end up with a file on your disk with the rightname of size 0. Closing the file properly sets the correct file size in theassociated directory entry.Character I/O- The simplest approach to file processing is to go through files character by character.- To read a single character you can use the function getc:int getc (FILE *infile);- To write a single character you can use the function putc:int putc (int c, FILE *infile);- Example: Copy one file to another by calling the following function:Files in C - 3void CopyFile(FILE *infile, FILE *outfile){ int ch; while( (ch = getc(infile)) != EOF){ putc(ch, outfile); } }Updating a fileSuppose you want to modify the contents of an existing file. The processof changing a file is called updating the file and is not as simple as itmight seem.The most common way to update a file consists of the following steps:1. Open the original file for input.2. Open a temporary file for output with a different name.3. Copy the input file to temporary file, performing any updates as you go.4. Close both files.5. Delete the original file.6.Rename the temporary file so that it once again has the original name.Example/* * This program copies a program from one file to * another, removing all comments . */#include<stdio.h>#include<string.h>#define TRUE 1#define FALSE 0void CopyRemovingComments (FILE *, FILE *);int main(){Files in C - 4char filename[20], *temp; FILE *infile, *outfile; printf("This program removes comments from a file.\n"); while (TRUE) { printf("File name: "); scanf("%s", filename); infile = fopen(filename,"r"); if (infile != NULL) break; printf("File %s not found. Try again.\n", filename); } temp = tmpnam(NULL); outfile = fopen(temp, "w"); if (outfile == NULL) printf("Error: Can't open temporary file.\n"); else { CopyRemovingComments(infile,outfile); fclose(infile); fclose(outfile); if (remove(filename) != 0|| rename(temp,filename) != 0) printf("Unable to rename temporary file."); }}void CopyRemovingComments (FILE *infile, FILE *outfile){ int ch, nch; int commentFlag;


View Full Document

UCF COP 3502H - Files and Libraries in the C Programming Language

Download Files and Libraries in the C Programming Language
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Files and Libraries in the C Programming Language and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Files and Libraries in the C Programming Language 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?