Random Access File Handling in C
Share
Programming Random Access File I/O in C
The basic file operations are - fopen - open a file- specify how its opened (read/write) and type (binary/text)
- fclose - close an opened file
- fread - read from a file
- fwrite - write to a file
- fseek/fsetpos - move a file pointer to somewhere in a file.
- ftell/fgetpos - tell you where the file pointer is located.
There are two fundamental types of file: text and binary. Of these two,
binary are generally the simpler to deal with. As doing random access
on a text file isn't something you need to do too often, we'll stick
with binary files for the rest of this lesson. The first four
operations listed above are for both text and random access files. The
last two just for random access. Random access means we can
move to any part of a file and read or write data from it without
having to read through the entire file. Back thirty years ago, much
data was stored on large reels of computer tape. The only way to get to
a point on the tape was by reading all the way through the tape. Then
disks came along and now we can read any part of a file directly.
Programming With Binary FilesA binary file is a file of any length that holds bytes with values in
the range 0 to 0xff. (0 to 255). These bytes have no other meaning
unlike in a text file where a value of 13 means carriage return, 10
means line feed, 26 means end of file and software reading text files
has to deal with these.
Download Example 1.
This shows a simple binary file being opened for writing, with a text
string (char *) being written into it. Normally you'd use a text file
for that but I wanted to show that you can write text to a binary file.
// ex1.c #include <stdio.h> #include <string.h> int main(int argc, char * argv[]) { const char * filename="test.txt"; const char * mytext="Once upon a time there were three bears."; int byteswritten=0; FILE * ft= fopen(filename, "wb") ; if (ft) { fwrite(mytext,sizeof(char),strlen(mytext), ft) ; fclose( ft ) ; } printf("len of mytext = %i ",strlen(mytext)) ; return 0; }
Comments:
|
Submitted By:
Prof: Software Engineer
Tech: C ,Cpp
|