Summary

This document explains file management concepts in C programming, focusing on file operations, creating files, reading and writing from files, and common file related errors. It presents code examples, function descriptions, and includes a table of common file handling functions in C.

Full Transcript

Department of First Year Engineering File Management in C Programming for Problem Solving (PPS) Department of First Year Engineering INTRODUCTION 1. When a data of large volume is handled using console oriented I/O functions, two major problems...

Department of First Year Engineering File Management in C Programming for Problem Solving (PPS) Department of First Year Engineering INTRODUCTION 1. When a data of large volume is handled using console oriented I/O functions, two major problems occur, a. It becomes cumbersome and time taking to handle large volumes of data through terminals. b. The entire data is lost when the program is terminated or the computer is turned off. 2. The above problems can be overcome by using the concept of files to store the data. 3. A file is a place on disk where a group of related data is stored. Department of First Year Engineering 4. C supports the following file operations by using a number of built-in functions. a. Naming a file b. Opening a file c. Reading data from a file d. Writing data to a file e. Closing a file Department of First Year Engineering STANDARD I/O FILE HANDLING LIBRARY FUNCTIONS Function Name Operation Creates a new file for use. fopen( ) Opens an existing file for use. Closes a file which has been opened for fclose( ) use. getc( ) Reads a character from a file. putc( ) Writes a character to a file. Department of First Year Engineering fprintf( ) Write a set of data values to a file. fscanf( ) Reads a set of data values from a file. getw( ) Reads an integer from a file. putw( ) Writes an integer to a file. Gives the current position in the file(in ftell( ) terms of bytes from the start). Sets the position to the beginning of the rewind( ) file. Department of First Year Engineering DEFINING AND OPENING A FILE 1. For defining and opening a file one must specify the following things about the file to the operating system, a. File Name b. Data Structure c. Purpose 2. It takes the general form as follows: FILE *fp; fp = fopen(“filename”, “mode”); 3. The first statement declares the variable fp as a “pointer to the data type FILE”. Department of First Year Engineering 4. The second statement opens the file having file name as filename and assigns an identifier to the FILE type pointer fp. This pointer fp works as a communication link between program and system. 5. The second statement also specifies the purpose of opening file by mentioning respective mode. The mode can be one of the following. Note :Both the file name and mode are specified as string, therefore must be enclosed in double quotes. Department of First Year Engineering Mode Meaning of Mode During Inexistence of file Open the file for If the file does not exist, fopen() r reading only returns NULL. If the file exists, its contents are Open the file for overwritten. W writing only If the file does not exist, it will be created. Open the file for If the file does not exist, fopen() a appending (or returns NULL. adding) data to it. Department of First Year Engineering CLOSING A FILE An already opened file for a specific purpose must be closed as soon as all operations on it have been completed, for the following reasons. 1. To ensure that all outstanding information associated with the file is flushed out from the buffers and all the links to the file are broken. 2. To prevent the file from any accidental misuse. 3. To open another file when a maximum limit on number of files that can be opened is reached. 4. To reopen the same file in a different mode. Department of First Year Engineering It takes the general form as, fclose(file_pointer); The above statement would close the file associated with the FILE pointer file_pointer. ………… ………… FILE *p1, *p2; p1 = fopen(“INPUT”, “w”); p2 = fopen(“OUTPUT”, “r”); …………. …………. fclose(p1); fclose(p2); Department of First Year Engineering INPUT/OUTPUT OPERATIONS ON FILES The getc and putc Functions 1. These are simplest file I/O functions. 2. For a file having pointer as fp1 and opened with w mode, following syntax can be used to write a character into it. putc(c, fp1); The above statement writes the character contained in the character variable c to the file associated with FILE pointer fp1. 3. Similarly, for a file having pointer as fp2 and opened with r mode, following syntax can be used to read a character from it. Department of First Year Engineering c = getc(fp2); The above statement would read a character from a file whose pointer is fp2 and would assign it to the character variable c. Note :1. The file pointer moves one character position for every operation of putc or getc. 2. The getc will return an end-of-file marker EOF, when end of file has been reached. 3. Therefore the reading should be terminated when EOF is encountered. Department of First Year Engineering #include // Reopen the file INPUT main( ) f1 = fopen(“INPUT”, “r”); { FILE *f1; // Read a character from INPUT char c; printf(“Data Input\n\n”); while((c = getc(f1)) != EOF) // Open the file INPUT f1 = fopen(“INPUT”, “w”); // Display a character on screen // Get a character from keyboard printf(“%c”, c); while((c=getchar()) != EOF) // Write a character to // Close the file INPUT INPUT putc(c, f1); fclose (f1); // Close the file INPUT } fclose(f1); printf(“\nData Output\n\n”); Department of First Year Engineering Output Data Input This is a program to test the file handling features on this system. Data Output This is a program to test the file handling features on this system. Department of First Year Engineering The getw and putw Functions 1. These file management functions are similar to getc and putc functions, and are used to read and write integer values. 2. These functions can be used while dealing with integer data only. 3. The general forms of getw and putw functions are: putw(integer, fp); getw(fp); Program File Link: https://drive.google.com/file/d/1iTY9z0zkvZ8ttX-NRNN30BovnwRBwOLZ/view?usp=shar e_link Department of First Year Engineering The fprintf and fscanf Functions 1. These file management functions are used to handle the mixed data simultaneously. 2. The functions fprintf and fscanf are identical to the familiar console oriented I/O functions printf and scanf but work on files. 3. The general forms of fprintf is: fprintf(fp, “control string”, list); Where, Fp is a file pointer associated with a file that has been opened for writing. Department of First Year Engineering The control string contains the output specifications for the items in the list. The list may contain variables, constants and strings. Exampl e: fprintf(f1, “%s%d%f”, name, age, 7.5); Here, name is an array variable of type char and age is an int variable 4. The general forms of fscanf fscanf(fp, is: “control string”, list); Department of First Year Engineering Exampl e: fscanf(f1, “%s%d”, item, &quantity); Program File Link: https://drive.google.com/file/d/1ECxZPwzRO7mJO_6YhV1DAcbH7CfKGTmE/vie w?usp=share_link Department of First Year Engineering ERROR HANDLING DURING I/O OPERATIONS 1. An error may occur during I/O operations on a file. 2. Following are the typical error situations: a. Trying to read beyond the end-of-file marker. b. Device overflow. c. Trying to use a file that has not been opened. d. Trying to perform an operation on a file, when the file is opened for another type of operation. e. Opening a file with invalid file name. f. Attempting to write to a write-protected file. 3. An unchecked program for these error may lead to premature termination and incorrect output if the Department of First Year Engineering 4. There are two status-inquiry library functions; feof and ferror that can be used to detect I/O errors. The feof Function 1. It is used to test for an end of file condition. 2. It takes FILE pointer as its only argument. 3. It returns a nonzero integer value if all of the data from the specified file has been read, and returns zero otherwise. Exampl e: if (feof(fp)) printf(“End of data.\ n”); Department of First Year Engineering The above statement would display the message “End of data.” on reaching the end of file condition of the file pointed by fp. The ferror Function 1. It is used to report the status of the file indicated. 2. It also takes FILE pointer as its only argument. 3. It returns a nonzero integer value if an error has been detected up to that point, during processing, and returns zero otherwise. Exampl e: if (ferror(fp) != 0) printf(“An error has occurred.\ n”); Department of First Year Engineering The above statement would display the message “An error has occurred.” if the reading is not successful. To Report Unopening of A File If a file is unable to open for some reason, then the functions fopen returns a NULL pointer. This feature can be used to test whether a file has been opened or not. Exampl e: if (fp == NULL) printf(“File could not be opened.\n”); Program File Link: https://drive.google.com/file/d/1Du7s1jbDn_RXdX_KcwO0zrejwZjZJFJ0/view Department of First Year Engineering RANDOM ACCESS TO FILES 1. Sometimes it is required to access only a part of a file instead of reading the whole file sequentially. 2. This can be achieved by using following Random Access Functions: a. ftell b. rewind c. fseek The ftell Function 1. This function is used to save the current position of the file. Department of First Year Engineering 3. It returns the number of type long, that corresponds to the current position. 4. It takes the general form as: n = ftell(fp); Here n would give the relative offset (in bytes) of the current position. This means the n bytes have already been read (or written). The rewind Function 1. It is used to rest the position of a file to the start. 2. It helps in reading the file more than once, without having to close and open the file. Department of First Year Engineering 3. It also takes the file pointer as its only argument. 4. It takes the general form as: rewind(fp); After the above statement if the current position of the file is found using n = ftell(fp), it (n) wold be zero because the current position has been set to the start Note of the file. :➔ The first byte in the file is numbered as 0, second as 1, and so on. ➔ Whenever a file is opened for reading and writing the, a rewind is done implicitly. Department of First Year Engineering The fseek Function 1. It is used to move the file position to a desired location within the file. 2. It takes the general form as. fseek(file_ptr, offset, position); Where, file_ptr is a pointer to the concerned file. offset is a variable or number of type long. position is an integer number. Department of First Year Engineering The position can take on of the following three values. Value Meaning 0 Beginning of file 1 Current Position 2 End of file Note :The offset may be positive, meaning move forwards, or negative, meaning move backwards. Department of First Year Engineering The table below shows the various operations fseek function. Statement Meaning fseek(fp,0L,0); Go to the beginning. (Similar to rewind) fseek(fp,0L,1); Stay at current position. (Rarely used) Go to the end of the file, past the last fseek(fp,0L,2); character of the file. fseek(fp,m,0); Move to (m+1)th byte in the file fseek(fp,m,1); Go forward by m bytes. Go backward by m bytes from the fseek(fp,-m,1); current position. Go backward by bytes from the end. Department of First Year Engineering Note :➔ After the successful operation on a file the fseek returns a zero. ➔ If the file pointer is attempted to move beyond the file boundaries, Program File an error occurs and fseek returns - Link:1. https://drive.google.com/file/d/12yOQfb9HWn4Qe-IISwkUm0JZmWJcLS0I/view ?usp=share_link

Use Quizgecko on...
Browser
Browser