In C, a file can refer to a disk file, a terminal, a printer, or a drive. In other words, a file represents a concrete device which you want to exchange information. A file is a region in hard or in auxiliary storage devices. It contains bytes of information.
Before you perform any communication to a file, you have to open a file. At the end, of the process, you need to close the file I/O is always done in a program in the following sequence.
Before performing any file I/O, the file must be opened. While opening the file, the following are specified.
The function of fopen is used to open a file. It accepts two strings, the first is the name of the file, and the second is the mode in which it should be opened.
Syntax:
FILE *ptvar
Here, File is a special structure type that establishes the buffer area and ptvar is a pointer variable that indicates the beginning of the buffer area. The structure type of FILE is defined within a system include file, typically stdio.h. The pointer ptvar is often referred to as stream pointer or simply a stream.
Example: Opening a file
FILE *fp;
fp = fopen (“outfile1.txt”,”w”);
*fp declares the pointer to the FILE structure. The structure is defined in <stdio.h>.
The function fopen returns a pointer to the FILE structure which it creates. This pointer must be used in subsequent operations on the files, such as reading from or writing to it. The FILE pointer fp, is also said to represent the stream of a file called outfile1.txt already exists, it is deleted and rewritten.
The file can be open in the following manner
File Type | Meaning |
“r” “w” “a” “r+” “w+” “a+” | Open an existing file for read only Open a new file for writing only Open an existing file for appending data elements Open an existing file for both reading and writing Open a new file for both reading and writing Open an existing file for both reading and appending. A new file will be created if the specified file does not exist |
Example: # Enter some characters through the keyboard and write them to the file and finally display them on the monitor.
#include <stdio.h> #include <conio.h> void main () { FILE *f1; char c; printf(“Data input\n”); printf(“\n PRESS CTRL+Z WHEN FINISHED ENTERING DATA\n\n”); F1=fopen(“input”,”w”); while ((c=getchar())!EOF) putc(c,f1); fclose (f1); printf(“\n Data output: \n”); f1=fopen (“input”, “r”); while ((c=getc(f1))! =EOF) printf(“%c”, c); fclose (f1); } |
When a file is created in output mode, the data or elements should be written to the disk in a specified file. The specified file has name and extension generally. The writing of the data from a keyboard is carried out by using the following functions.
Fwrite appends a specified number of equal-sized data items to an output file.
Syntax: size_t (fwrite const void * ptr,size-t size, size_t n, FILE * stream);
The function fprintf writes to the files associate with the file stream.
Syntax: int fprintf(FILE *stream, const char * format [, argument,…., argument]);
Example: # Write a program to accept an integer and save in file outfile.txt
#include <stdio.h> void main () { int i; FILE *fp=fopen (“outfile1.txt”,”w”); printf(“\n Input an integer:”); scanf(“%d”, &i); fprintf(fp, “%d\n”, i); fclose (fp); } |
Here, fprintf function writes the variable to the file as printf writes to the screen.
The function of scanf, gets, getc are used to read from the standard input. To read from a file, the functions fscanf, fgets, and fgetc are used. All these functions accept a FILE pointer (obtained from fopen), as their first parameter, in addition to the parameters required by the standard input functions.
Example 3: # Write a program to open “outfile.txt” in read mode and display its content.
#include <stdio.h> void main () { int i; FILE *fp=fopen (“outfile1.txt”, “r”); fscanf(fp, “%d”, &i); printf(“The integer in the outfile is %d”, i); fclose (fp); } |
The file handling function used are:
Writing | Reading | Used as |
fputc() fputs() fpirntf() fwrite() write() | fgetc() gets() fscanf() fread() read() | Individual characters Character string Formatted ASCII Binary files Low level binary |
Example: # Enter a formatted data as name, age, and roll through the keyboard and write them to a file and display them on the monitor.
/* program to write and retrieve records from a file */ /* create a file in write mode */ #include <stdio.h> typedef struct { char name[50]; unsigned int age; unsigned int rollno; } st_rec; void main (void) { st_rec rec; FILE *fp; fp=fopen (“class.rec”,”w”); printf(“\n Enter Name, Age and Roll Number separated with space \n”); printf(“\n type Ctrl+Z to stop \n”); /* read form keyboard and write to file */ while ((scanf(“%s %u”, rec.name, &rec.age, &rec.rollno))!=EOF) fwrite(&rec, sizeof (rec), 1, fp); fclose (fp); printf(“\n”); /* read form file and write on screen */ fp=fopen (“class.rec”, “r”); /*while (fread (&rec, sizeof (rec), 1, fp)) printf(“%-10s %5u %3u\n”, rec.name, rec.age, rec.rollno); fclose (fp); } |
When a C program begins execution, the following data streams (pointer to FILE structures) will be automatically opened (these files are constants and not variables).
stdin stdout stderr stdaux stdprn | opening input device open for output device open for error output device open for an auxiliary device (I/O) open printer for output |
During a write to a file, the data written is not put on the disk immediately. It is stored in a buffer. When the buffer is full, all its contents are actually written to the disk. The process of emptying the buffer by writing its contents to the disk is called flushing the buffer.
Closing the file flushes the buffer and releases the space taken by the FILE structure which is returned by fopen. If a particular FILE pointer is not required after a certain point in a program, pass it to the fclose and close the file.
#Write a program to demonstrate opening a file in append mode, read and write a file.
/* file handling in append mode, read and write to a file */ #include <stdio.h> void main () { FILE *fp char name[20]; unsigned int mark; /* file STUREC is open in append mode */ fp=fopen(“STUREC”,”a”); /* PRESS CTRL+Z IN DOS, CTRL+D IN UNIX */ printf(“Use Ctrl+D or Ctrl+Z to stop entry\n”); printf(“Enter name and space bar and mark”); while ((scanf(“%s %u”, name, &mark))!=EOF) /* writing student name to file STUREC*/ fprintf(fp, “%s %u”, name, mark); fclose (fp); printf(“\n”); /* opening the file for read mode */ fp=fopen(“STUREC”,”r”); printf(“ NAME MARK \n”); printf(“………………………………..”); while ((fscanf(fp, “%s %u”, name, &mark ))!=EOF) /* display file content */ printf(“%+10s %3u \n”, name, mark); fclose (fp); } |
# Write a program to write student reg_no, name and mark into a data file and read from it.
/*program to write and retrieve records from a file */ /* create a file in write mode */ #include <stdio.h> typedef struct { unsigned int reg_no; char name[50]; unsigned int mark; } st_rec; void main (void) { st_rec rec; FILE *fp; fp=fopen (“class.rec”,”w”); printf(“\n Enter register number, name and mark separated with space \n”); printf(“\n type Ctrl+Z to stop \n”); /* read from keyboard and write to file */ while (( scanf(“%u %s %u”, &rec.regno, rec.name, &rec.mark))!=EOF) fwrite (&rec, sizeof (rec), 1, fp); fclose (fp); printf(“\n”); /* read from file and write on screen */ fp=fopen (“class.rec”,”r”); /* while loop terminates when fread return 0 */ while (fread (&rec, sizeof (rec), 1, fp)) printf(“%5u, %-10s %3u\n”, rec.reg_no, rec.name, rec.mark); fclose (fp); } |
(Khanal)
Bibliography
Khanal, R.C. Khanal, R.C. Computer Concept for XII. Pashupatigriha Marga, Thapathali, Kathmandu, Nepal: Ekta Books Distributors Pvt. Ltd., 2010. 281-285.
.
ASK ANY QUESTION ON File Handling in C
No discussion on this note yet. Be first to comment on this note