
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Random Accessing Files in C Language
Random accessing of files in C language can be done with the help of the following functions −
- ftell ( )
- rewind ( )
- fseek ( )
ftell ( )
It returns the current position of the file ptr.
The syntax is as follows −
int n = ftell (file pointer)
For example,
FILE *fp; int n; _____ _____ _____ n = ftell (fp);
Note − ftell ( ) is used for counting the number of characters which are entered into a file.
rewind ( )
It makes file ptr move to beginning of the file.
The syntax is as follows −
rewind (file pointer);
For example,
FILE *fp; ----- ----- rewind (fp); n = ftell (fp); printf ("%d”, n);
Output
The output is as follows −
0 (always).
fseek ( )
It is to make the file pntr point to a particular location in a file.
The syntax is as follows −
fseek(file pointer, offset, position);
Offset
- The no of positions to be moved while reading or writing.
- If can be either negative (or) positive.
- Positive - forward direction.
- Negative – backward direction.
Position
It can have three values, which are as follows −
- 0 – Beginning of the file.
- 1 – Current position.
- 2 – End of the file.
Example
fseek (fp,0,2) - fp moved 0 bytes forward from the end of the file.
fseek (fp, 0, 0) – fp moved 0 bytes forward from beginning of the file
fseek (fp, m, 0) – fp moved m bytes forward from the beginning of the file.
fseek (fp, -m, 2) – fp moved m bytes backward from the end of the file.
Errors
The errors related to fseek () function are as follows −
- fseek (fp, -m, 0);
- fseek(fp, +m, 2);