0% found this document useful (0 votes)
53 views

File Operations: Objectives

This document summarizes file operations in C including opening, reading, and writing to files. It discusses library functions like fopen(), fclose(), getc(), putc(), fscanf(), fprintf() for performing input/output operations on files. It also covers passing command line arguments, opening files in different modes, reading/writing characters and integers, error handling functions like feof() and ferror(), and random access functions like ftell() and fseek() to manipulate the file position pointer.

Uploaded by

alysonmicheaala
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

File Operations: Objectives

This document summarizes file operations in C including opening, reading, and writing to files. It discusses library functions like fopen(), fclose(), getc(), putc(), fscanf(), fprintf() for performing input/output operations on files. It also covers passing command line arguments, opening files in different modes, reading/writing characters and integers, error handling functions like feof() and ferror(), and random access functions like ftell() and fseek() to manipulate the file position pointer.

Uploaded by

alysonmicheaala
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 10

File Operations

15. FILE OPERATIONS


Objectives
Library Functions for File I/O More Library Functions Command Line Arguments

This lesson covers reading and writing to files and passing command line arguments into your code. An important part of any program is the ability to communicate with the world external to it. Reading input from files and writing results to files are simple, but effective ways to achieve that. Command line arguments provide a way to pass a set of arguments into a program at run time. These arguments could be the names of files on which to operate, user options to modify program behavior, or data for the program to process. 8.1 Library Functions for File I/O This section introduces the library functions used for file input and output (I/O). These routines are used to open and close files and read and write files using formatted I/O. Formatted I/O was introduced in module 4. You may wish to review that material. Function Meaning fopen() fclose() getc() putc() getw() putw() fscanf() fprintf() ftell() Fseek() Creates a new file. Opens an existing a file. Closes a file that has been opened for use. Reads a single character from a file. Writes a single character to a file. Reads an integer from a file. Writes an integer to a file. Reads a set of values from a file. Writes a set of values to a file. Gives the current position in a file. Sets the cursor to a specified location in a file.

rewind() Sets the cursor to the beginning of a file Three important points of a file: 1. File name 2. Data structure 3. Purpose The file name has 2 parts. They are primary part and extension. For example, sample.txt first.c

File Operations test.c Here, sample, first and test are primary part of the file names and txt and c are extensions of the files. All the files are defined under the structure called *FILE. FILE *fp; fp is a file pointer defined as a type of FILE. Purpose: When we open a file, we have to specify the purpose for which we are opening that file. fopen fopen is used to open a file for formatted I/O and to associate a stream with that file. A stream is a source or destination of data. It may be a buffer in memory, a file or some hardware device such as a port. The prototype for fopen is: FILE *fp; fp=fopen(filename,mode); fopen returns a file pointer on success or NULL on failure. The file pointer is used to identify the stream and is passed as an argument to the routines that read, write or manipulate the file. The filename and mode arguments are standard null-terminated strings. The valid modes are shown below. Mode Use R W A R+ W+ A+ open for reading open or create for writing. Truncate (discard) any previous contents. open or create for writing. Append (write after) any previous contents. open file for update (reading and writing). open or create file for update. Truncate (discard) any previous data. open or create file for update. Append (write after) any previous data.

For example, FILE *fp1, *fp2; fp1=fopen(sample,r); fp2=fopen(data,w); the file sample is opened for reading and data is opened for writing. fflush fflush is used to flush any buffered data out of an output stream. Output streams may be buffered or unbuffered. With buffered output, as data is written to the stream, the operating system saves this data to an intermediate buffer. When this buffer is full, the data is then written to the file. This is done to reduce the number of system calls needed to write out the data. The whole buffer is written at once. This is done to make the program more efficient and without any programmer involvement. Fflush forces the buffer to be written out to the associated file. Its prototype is: int fflush(FILE *stream);

File Operations It accepts a file pointer as an argument. It returns zero on success and EOF on failure. EOF is a special constant used to designate the end of a file. fclose A file must be closed as soon as all operations on it have been completed. Files are closed with the function fclose. Its prototype is: fclose(file_pointer); fclose returns zero on success and EOF on failure. 8.2 More Library Functions getc This function returns the next character in the input stream, or EOF if the end of the file is encountered. It returns int rather than char because the "end of file", EOF, character must be handled. EOF is an int and is too large to fit in a char variable. The end of data id indicated by entering an EOF character, which is control-Z in the reference system. The general format of getc is: getc(filepointer); for example, char c; fp=fopen(Text,r); while((c=getc(fp))!=EOF) putchar(c ); This reads the characters from the file Text and displays it on the screen. putc putc writes a single character to the output stream. It returns EOF on failure. The general format is: putc(char,filepointer); for example, char c; fp=fopen(Text,w); while((c=getchar())!=EOF) putc(c,fp); This writes the characters to the file Text. Program: #include <stdio.h> main() { char c; FILE *fp; fp=fopen(Text,w); printf(\n Enter the characters that ended with EOF character\n); while((c=getchar())!=EOF)

File Operations putc(c,fp); fclose(fp); fp=fopen(Text,r); printf(\n Display the characters\n); while((c=getc(fp))!=EOF) putchar(c); fclose(fp); } Output: Enter the characters that ended with EOF character Hello world Display the characters Hello world getw and putw functions The getw and putw are integer-oriented functions. The general forms of getw and putw are: getw(fp); putw(integer,fp); Program: #include<stdio.h> main() { FILE *f1, *f2, *f3; int number,m; f1=fopen(Data,w); for(m=1;m<=10;m++) { scanf(%d,&number); putw(number,f1); } fclose(f1); f1=fopen(Data,r); f2=fopen(Odd,w); f3=fopen(Even,w); while ((number=getw(f1))!=EOF) { if(number%2==0) putw(number,f3); else putw(number,f2); } fclose(f1); fclose(f2); fclose(f3); f2=fopen(Odd,r);

File Operations f3=fopen(Even,r); printf(\n Contents of Odd file\n); while ((number=getw(f2))!=EOF) putw(number,f2); fclose(f2); printf(\n Contents of Odd file\n); while ((number=getw(f3))!=EOF) putw(number,f3); fclose(f3); } Output: 12 23 90 15 67 89 24 5 20 100 Contents of Odd file 23 15 67 89 5 Contents of Even file 12 90 24 20 100 fscanf Data is read from a file using fscanf. This function is very similar to scanf, which was described in lesson 4 and is used to read from standard input, stdin. Fscanf has one additional argument to specify the stream to read from. Remember that the argument to store data must be pointers. The prototype for fscanf is: fscanf(filepointer,control string,&arg1,&arg2,....); The arguments are valid C variables. This statement reads the value of arg1, arg2 from the file pointed by the file stream. For example, int a; float b; char c; fp=fopen(Sample,r); fscanf(fp,%d%f%c,&a,&b,&c); This will read the values of a, b and c from the file pointed by fp. fprintf Data is written to a file using fprintf. This function is very similar to printf, which is described fully in lesson 4. Printf was used to write to standard output, stdout. fprintf has one additional argument to specify the stream to send data. Its prototype is: fprintf(filepointer, control string,&arg1,&arg2,....); fprintf returns the number of characters written if successful or a negative number on failure. For example, int a=20; float b=9.24; char c=v; fp=fopen(Sample,w); fprintf(fp,%d%f%c,a,b,c);

File Operations This will write the values of a, b and c to the file pointed by fp. Example The following program opens a file containing a name and an ID number. It then opens an output file and writes this data to an output file. This input file was created with a text editor.

Here is the example program. #include <stdio.h> int main() { char ifilename[] = "c:/lesson13_in.txt"; char ofilename[] = "c:/lesson13_out.txt"; char name[30]; int idNum; FILE *ofp, *ifp; /* Open file for input */ ifp = fopen(ifilename,"r"); /* Read data */ fscanf(ifp,"%s %d",name,&idNum); /* Open file for output */ ofp = fopen(ofilename,"w"); /* Write out data */ fprintf(ofp,"%d %s\n",idNum, name); /* Close Files */ fclose(ifp); fclose(ofp); return 0; } Here is the Output.

File Operations

Error handling during I/O operations It is possible that an error may occur during I/O operations on a file. Typical error situations include: Trying to read beyond the end-of-file mark. Divice overflow. Trying to use a file that has not been opened. Opening a file with an invalid filename. Trying to perform an operation on a file, when the file is opened for another type of operation. feof The feof function can be used to test for an end of file condition. It returns a nonzero integer If allof the data from the file has been read. Otherwise it will return 0. General format is: feof(fp) ferror The ferror function reports the status of the file indicated. It returns nonzero if an error has been detected up to that point, during processing. It returns 0 otherwise. General format is: ferror(fp); Random access functions ftell ftell take a file pointer and return a number of type long, that corresponds to the current position. This function is useful in saving the current position of a file, which can be used later in the program. It takes the following form: n=ftell(filepointer); n would give the relative offset (in bytes) of the current position. This means that n bytes have already been read (or written). rewind The general form is: rewind(filepointer); This would sets the file position to the start of the file. For example, rewind(fp);

File Operations n=ftell(fp); would assign 0 to n. Because the first byte in the file is numbered a 0, second as 1 and so on. fseek The general form is: fseek(file pointer, offset, position); offset is a number or variable of type long, and position is an integer number. The offset specifies the number of positions to be moved from the location specified by position. The position can take one of the following three values: Value Meaning 0 1 2 Beginning of file Current Position End of file Meaning Go to the beginning. Stay at the current position Go to the end of the file Move to (m+1)th byte in the file. Go forward by m bytes. Go backward by m bytes from the current position. Go backward by m bytes from the end..

Operations of fseek function Statement Fseek(fp,0L,0); fseek(fp,0L,1); fseek(fp,0L,2); fseek(fp,m,0); fseek(fp,m,1); fseek(fp,-m,1); fseek(fp,-m,2);

8.3 Command Line Arguments C provides a mechanism to pass command line arguments into a program when it begins to execute. When execution begins, "main" is called with two arguments, a count and a pointer to an array of character strings. For example, the main function with arguments is: main(int argc, char * argv[]) The first argument argc is known as argument counter represents the number of arguments in the command line. The second argument argv is known as argument vector is an array of char type pointers that points to the command line arguments. The pointer is usually called argv. The use of argv is somewhat tricky. Since argv is a pointer to an array of character strings, the first character string is referenced by argv[0] (or by *argv). The second character string is referenced by argv[1] (or by *(argv + 1)), the third by argv[2], and so on. The first character string, argv[0], contains the program name. Command line arguments begin with argv[1]. If the number of arguments will be fixed, the count, argc, should

File Operations always be checked. Here is a simple example program that performs an echo. Note that the number of strings to echo need not be hard coded. For instance, For the command line C > exam data results The value of argc would be 3 and the argv would be an array of three pointers to strings as shown below: argv[0] -----> exam argv[1] -----> data argv[2] -----> results Note that argv[0] always represents the command name that invokes the program. Program: #include <stdio.h> int main(int argc, char *argv[]) { int i; printf("The number of command line arguments is %d\n", argc); printf("The program name is %s\n",argv[0]); printf(Arguments are\n); for (i=1; i < argc; i++) { printf("%s",argv[i]); } printf("\n"); return 0; } Output: c>com aaa bbb ccc ddd The number of command line arguments is 5 The program name is com Arguments are aaa bbb ccc ddd Summary A file must be opened before it can be used. When an existing file is opened using w mode, the contents of file are deleted. When a file is used for both reading and writing, we must open it in w+ mode. EOF is integer type with a value 1. Therefore, we must use an integer variable to test EOF. It is an error to omit the file pointer when using a file function. It is an error to try to read from a file that is in write mode and vice versa. It is an error to open a file for reading when it does not exist.

File Operations It is a good practice to close all files before terminating a program.

Review Questions State whether true or false 1. A file must be opened before it can be used. 2. Files always referred to by name in C program. 3. The function fseek is used to tell the current position of a file. 4. The mode w is used to append the data in a file. Fill in the blanks 1. The function _________ is used to position a file at the beginning. 2. The function _________ gives the current position in the file. 3. The mode _________ is used for opening a file for updating. 4. The function _________ is used to read a single character from a file. 5. The function _________ is used to read a single integer from a file. Programming Exercises 1. Write a program to copy the contents of one file to another. 2. Write a program that appends one file at the end of other. 3. Write a program to store the command line arguments in a file.

You might also like