Cds Unit 6
Cds Unit 6
Unit VI
Files
A file is an external collection of related data treated as a unit. The primary purpose of a file is to keep a record of data. Since he contents of primary memory are lost when the computer is shut down, we need files to store our data in a more permanent form. Files are stored in auxiliary or secondary storage devices. The two most common forms of secondary storage are disk and tape. When the computer reads, the data move from the external device to memory; when it writes, the data move from memory to the external device. This data movement often uses a special work area called buffer. A buffer is a temporary storage area that holds data while they are being transferred to or from memory. As a file is being read, there eventually comes a point when all the data have been input. At the point, the file is said to be at end of file. The end of file in an auxiliary storage device is detected automatically by the device and passed to the programs. It is the programmers job to test for end of file. Every operating system uses a set of rules for naming its files. When we want to read or write auxiliary storage files, we must use the name of the file. We refer this as file name. A program that reads or write files needs to know several pieces of information, such as the file name, the position of the current character in the file and so on. C has predefined a file structure to hold this information. The stdio.h header file defines the file structure; its identifier is FILE. When we need a file in our program, we declare it using FILE type.
Streams
Although the source and destination of data is a file or a physical device in C. Data is input to and output from a stream. A stream can be associated with a physical device such as a terminal, or with a file stored in auxiliary memory.
Create the Stream A stream is created when we declare it. The declaration uses the FILE type as shown below
I YEAR B.TECH CSE
Page 1
N.Vamshi Krishna
Unit VI
FILE* spDate; In this example, spData is a pointer to the stream. The sp stands for stream pointer. Asterick after FILE indicates that spData is a pointer variable that contains the address of the stream created. It is an error to omit the asterick. Opening a File Once a stream has been created, we are ready to associate the stream to a file. When the file is opened, the stream and the file are associated with each other, and the FILE type is filled with pertinent file information. Using the Stream Name After a stream is created, the stream pointer is used in all functions that are needed to access the corresponding file input or output. Closing the Stream When the file processing is complete, we close the file. Closing the file breaks the association between the stream name and the file name. After the close, the stream is no longer available and any attempt to use it results in an error.
These streams are created when the program starts and we cannot declare them. The association between the three standard streams and the keyboard and the monitor is also done automatically when the program starts. There is no need to open and close the standard streams. It is done automatically by the operating system. C includes many standard functions to input data form the keyboard and output data to the monitor automatically without the need for explicitly using these standard streams. Examples of such functions are scanf and printf.
Page 2
N.Vamshi Krishna
Unit VI
5. Block Input/Output Functions 6. File Positioning Functions 7. System File Operations 8. File Status Operations
To open a file, we need to specify the physical filename and its mode, as shown below fopen(filename, mode); The filemode is a string that tells C how we intend to use the file. A filename is a string that supplies the name of the physical file as it is known to the external world. The address of the file structure that contains the file information is returned by fopen. The actual contents of FILE are hidden from our view. Ex : spData = fopen(MyFile.doc, w); The stream pointer spData is assigned the address of the file structure when we open the file; the return value from the fopen function contains the file structure address. File Modes When we open a file, we explicitly define its mode. The mode shows how we will use the file : for reading, for writing, or for appending. C has six different file modes. Mode Read Only Symbol r Meaning Open text file in read mode Write Only w If file exits, the marker is positioned at beginning.
If file doesnt exist, error returned Open text file in write mode. If file exits, the previous data is erased and positioned at beginning.
Append Only
If file doesnt exist, it is created. Open text file in append mode If file exits, the marker is positioned at end.
Read and Write Write and Read Append and Read File Close
r+ w+ a+
If file doesnt exist, it is created. Opens text file for reading as well as writing modes. Opens text file for writing as well as reading modes. Opens text file for reading as well as appending modes.
When a file is no longer needed, it should be closed to free system resources such as buffer space. A file is closed using close function, fclose, it is declared as follows fclose(stream pointer); The example is as follows
I YEAR B.TECH CSE
Page 3
N.Vamshi Krishna
Unit VI
fclose(spData); Open and Close File Errors Open and close errors occur for a number of reasons. One of the most common errors occurs when the external filename in the open function call does not match a name on the disk. When we create a new file, the open fails if there isnt enough room on the disk. Always check to make sure that a stream has opened successfully. If it has, then we have a valid address in the file variable. But if it failed for any reason, the stream pointer variable contains NULL, which is a C-defined constant for no address in stdio.h. The fclose function returns an integer that is zero if the close succeeds and EOF if there is an error. EOF is defined in the stdio.h. Traditionally it is -1 but the standard defines it in any non character value.
N.Vamshi Krishna
Unit VI
Page 5
N.Vamshi Krishna
Unit VI
Write a character : putc and fputc The put functions write a character to the file stream specified, which can be user defined stream, stdin or stderr. For fputc, the first parameter is the character to be written and the second parameter is the file. If the character is successfully written, the function returns it. If any error occurs, they return EOF. The prototype functions are as follows int putc(int oneChar, FILE* spOut); int fputc(int oneChar, FILE* spOut); Ex : fputc(ch, spMyFile); 1. /*Program to create a text file */ #include<stdio.h> void main() { FILE* fp; int c; clrscr(); fp=fopen("one.c","w"); if(fp==NULL) { printf("cannot open file"); exit(); } while((c=getchar()) != EOF) fputc(c, fp); fclose(fp); printf("From file:"); fp=fopen("one.c","r"); if(fp==NULL) { printf("cannot open file"); exit(); } while((c=fgetc(fp)) != EOF) printf("%c",c); fclose(fp); getch(); } Output C programming and Data structures ^Z From File : C Programming and Data structures 2. /*Program to display contents of file*/ #include<stdio.h> void main() { FILE *fp; char ch; clrscr(); fp=fopen("one.txt","r"); if(fp==NULL) { printf("cannot open file");
I YEAR B.TECH CSE
Page 6
N.Vamshi Krishna
Unit VI
3. /*Program to copy contents of one file to another*/ #include<stdio.h> void main() { FILE *fp1, *fp2; char ch; clrscr(); fp1=fopen("one.txt","r"); fp2=fopen("two.txt","w"); if(fp2==NULL || fp1==NULL) { printf("cannot open file"); exit(); } while((ch=fgetc(fp1)) != EOF) fputc(ch, fp2); fclose(fp1); fclose(fp2); } 4. /*Program to reverse n contents of file*/ #include<stdio.h> void main() { FILE *fp; char ch,fname[20],nchars[30]; int i,n; clrscr(); printf("Enter the file name :"); scanf("%s",fname); fp=fopen(fname,"r"); if(fp==NULL) { printf("cannot open file"); exit(); } printf("Enter no. of characters to be read : "); scanf("%d",&n); for(i=0; i<n; i++) { ch=fgetc(fp); nchars[i]=ch; } nchars[i]='\0'; fclose(fp); strrev(nchars); printf("Reverse = %s",nchars); getch(); } Output
I YEAR B.TECH CSE
Page 7
N.Vamshi Krishna
Unit VI
Enter file name : one.txt Enter no.of characters to be read : 6 Reverse = ihsmav
5. /*Program to merge contents of two files to third file*/ #include<stdio.h> void main() { FILE *fp1, *fp2, *fp3; char ch; clrscr(); fp1=fopen("comp.c","r"); fp2=fopen("count.c","r"); fp3=fopen("three.txt","a"); if(fp1==NULL || fp2==NULL) { printf("cannot open file"); exit(); } while((ch=fgetc(fp1))!=EOF) { fprintf(fp3,"%c",ch); } fclose(fp1); while((ch=fgetc(fp2))!=EOF) { fprintf(fp3,"%c",ch); } fclose(fp2); fclose(fp3); getch(); }
Page 8
N.Vamshi Krishna
Unit VI
they are stored in memory. Binary files are read and written using binary streams known as block input/output functions.
Differences between Text and Binary Files Text File All data in a text file are human-readable graphic characters. Each line of data ends with a new line character. There is a special character called end-of-file (EOF) marker at the end of the file. State of a File An opened file is either in a read state, a write state, or an error state. If we want to read from a file, it must be in the read state. To open a file in the read state, we specify the read mode in the open statement. A file opened in the read mode must already exist. If it doesnt then the open fails. A file can be opened in the write state using either the write or append mode. In write mode, the writing starts at the beginning of the file. If the file already exists, its data are lost. In append mode, the data are added at the end of the file. In addition to read, write and append files can be opened in the update mode. Updating allows a file to be both read and written. To open a file for updating, we add a plus sign(+) to basic mode. The initial state of a file opened for updating is determined by the basic mode : r+ opens the file in the read state, while w+ and a+ open the file in write state Opening Binary Files The basic open operation is unchanged for binary files only the mode changes. The function declaration for fopen is repeated here for convenience FILE* fopen(const char* filename, const char* mode); To indicate the file is binary, we add a binary indication (b) to the mode. The six binary file modes are : read binary (rb), write binary (wb), append binary (ab) , read and updata binary (r+b), write and update binary (w+b), and append and update binary (a+b). Few examples are spReadBin = fopen(myFile.txt, rb); spWriteUp = fopen(myFile.txt,w+b); Closing Binary Files Just like text files, binary files must be closed when they are not needed anymore. Closing destroys the file table and erases the logical file name. The function declaration of the close function is given below int fclose(FILE* sp); Binary File Data are stored in the same format as they are stored in memory. There are no lines or new line characters. There is an end-of-file marker.
Page 9
N.Vamshi Krishna
Unit VI
The C language uses the block input and output functions to read and write data to binary files. When we read and write binary files, the data are transferred just as they are found in memory. There are no format conversions. The block read function is file read (fread). The block write function is file write (fwrite). File Read : fread The function fread whose declaration is shown below reads a specified number of bytes from a binary file and places them into memory at the specified location. int fread(void* pInArea, int elementSize, int cout, FILE* sp); The first parameter, pInArea is pointer to the input area in memory. The next two elements, elementSize and count are multiplied to determine how much data are to be transferred. The size is normally specified using the sizeof operator and the count is normally one when reading structures. The last parameter is the associated stream. The fread does not return end of file it returns the number of elements read. C provides another input/output function feof to test for end of file. File Write : fwrite The function fwrite whose declaration is shown below, writes a specified number of items to a binary file. int fwrite(void* pInArea, int elementSize, int cout, FILE* sp); Functionally, fwrite copies elementSize x count bytes from the address specified by pOutArea to the file. It retusn the number of items written. If the number of items written is fewer than count, then an error has occurred. Depending on the device we are working with, it may be possible to repeat the write, but generally the program should be aborted when we get a write error.
Page 10
N.Vamshi Krishna
Unit VI
When an error occurs, the subsequent calls to ferror return nonzero, until the error status of the file is reset. The function clearer is used for this purpose. The function declaration is as follows void clearer(FILE* stream);
Positioning Functions
Positioning Functions have two uses. First, for randomly processing data in disk files, we need to position the file to read the desired data. Second, we can use positioning functions to change a files state. Rewind File : rewind The rewind function simply sets the file position indicator to the beginning of the file. The function declaration is as follows; void rewind (FILE* stream); A common use of the rewind function is to change a work file from a write state to a read state. Often it is necessary to place data in a file temporarily for later processing. When all the data have been written and we are ready to begin reading, we rewind the file and simply start reading. Current Location : ftell The ftell function reports the current position of the file marker in the file, relative to the beginning of the file. It measures the position in the file by the number of bytes, relative to zero, from the beginning of the file. The function declaration for ftell is as follows : long int ftell(FILE* stream); Note that ftell returns a long integer. This is necessary because many files have more than 32,767 bytes, which is the maximum integer value on many computers. Ex: numChar = ftell(sp); If ftell encounters an error, it returns -1. Only two conditions cause an error. First, using ftell with a device that cannot store data, such as keyboard. Second, when position is larger than can be represented in a long integer. The primary purpose of ftell is to provide a data address(offset) that can be used in a file seek. It is especially useful when we are dealing with text files for which we cannot calculate the position of data. Set Position : fseek The fseek function positions the file location indicator to a specified byte position in a file. It gets its name from the disk-positioning operation, seek. Seek moves the access arm on a disk to a position in the file for reading or writing. The function declaration is as shown below int fseek(FILE* stream, long offset, int wherefrom); The first parameter is a pointer to an open file. Since the seek is used with both reading and writing files, the file state can be either read or write. The second parameter is a signed integer that specifies the number of bytes the position indicator must move absolutely or relatively. The third parameter is based on three constants that specify the starting point of the seek #define SEEK_SET 0 #define SEEK_CUR 1 #define SEEK_END 2
Page 11
N.Vamshi Krishna
Unit VI
Ex :
The above example points to the 99 bytes from the beginning of file. We can also use 0, 1, 2 in place of SEEK_SET, SEEK_CUR, SEEK_END -o0o-
Page 12
N.Vamshi Krishna