- A file is a place on disk, where group of related data is stored.
- Two different types of data files exist in C
- Stream-oriented(standard) data files.
- System-oriented(Low-level) data files.
- Stream oriented data files are of two types
- Data files comprising of consecutive charecters.
- Unformatted data files.
- System-oriented data files are more closely related to the computers operating system.
- System oriented files are complicated to work with, their usage is comparitively limited to certain particular applications.
Basic file operations in C
- Naming a file
- Opening a file
- reading data from a file
- writing data to a file
- closing a file.
Basics
- Before using a file, a buffer area has to be established for that file.The information is normally stored in 'buffer area' while its transfer between computer memory and datafile is being taken.
- The statement for establishing such an area is FILE *ptrvar;
- ptrvar is pointer variable name.
- FILE is a defined data type.
Opening a file
FILE *ptrvar;
ptrvar=fopen("filename","mode");
File opening Mode |
Meaning |
"r" |
open an existing file read only |
"w" |
open a new file for write only |
"a" |
open an existing file appending |
"r++" |
open an existing file for both reading and writing |
"w+" |
open a new file for both reading and writing |
"a++" |
open an existing file for both reading and appending |
Example
#include<stdio.h>
FILE *ptr;
ptr=fopen("file.txt",w);
- fopen opens the file 'file.txt' and associates it with the pointer ptr.
- "w" stands for the mode 'write-only'.
closing a datafile
- fclose(ptrvar); whrere ptrvar is pointer variable name.
Example
#include<stdio.h>
main()
{
union number
{
int one;
char two;
};
union number val;
val.one=300;
printf("val.one=%d",val.one);
printf("val.two=%d",val.two);
}
Output
value.one=300
value.two=44