Last Updated on July 2, 2023 by Mayank Dham
The C programming language offers a variety of functions that enable working with random access file in C, which grant programmers the ability to read from or write to any position within the file. This article will delve deeper into the concept of random access file in C and explore its functionalities.
What are Files?
In programming languages, files are utilized for long-term data storage or data transfer purposes. The method of accessing a file varies depending on the type of file system employed to retrieve data stored within the file.
Types of Files
Sequential files and random access files are two common ways of organizing data in computer systems.
Sequential file:
Sequential file is a type of file organization in which data is stored in a continuous manner, one record after the other, and each record is accessed in sequence. In a sequential file, data is read from the beginning of the file and is processed in the order it appears in the file. This type of file is best suited for applications where data is processed sequentially and not randomly accessed.
Random Access file:
In C language, a random access file allows us to read or write any data in our disc file without reading or writing every piece of data before it. We can quickly search for data, edit it, or even delete it in a random-access file. We can open and close random access files in C using the same opening mode as sequential files, but we need a few new functions to access files randomly.
Functions in random access file:
Thus, the following three functions assist in accessing the random access file in C:
- ftell()
- fseek()
- rewind()
1. ftell():
It is a standard C library function used to get the current position of the file pointer in a random access file. The function takes a file pointer as its argument and returns the current position of the file pointer, representing the number of bytes from the beginning of the file.
Syntax for ftell():
pos=ftell(FILE *fp)
Explanation of Syntax for ftell():
Where pos contain the current position or the number of bytes read, and fp is a file pointer.
Example for ftell():
#include<stdio.h> int main() { FILE *fp; fp=fopen("prepbytes.txt","r"); if(!fp) { printf("Error: File cannot be opened\n") ; return 0; } printf("Position pointer in the beginning : %ld\n",ftell(fp)); char ch; while(fread(&ch,sizeof(ch),1,fp)==1) { printf("%c",ch); } printf("\nSize of file in bytes is : %ld\n",ftell(fp)); fclose(fp); return 0; }
Output:
Position pointer in the beginning : 0
prepbytes
Size of file in bytes is : 9
Explanation for ftell():
First, let us create a file – prepbytes.txt which contains the data: prepbytes.We can observe that in the beginning, ftell returns 0 as the pointer points to the beginning and after traversing completely we print each character of the file till the end, and now ftell returns 9 as it is the size of the file.
2. fseek():
The fseek() function is a standard library function in the C programming language. It is used to set the file position indicator to a specified position in a file, allowing the program to read or write data from that position.
Syntax for fseek():
int fseek(FILE *fp, long offset, int whence);
Explanation of Syntax for fseek():
Here, stream is a pointer to the file stream that needs to be positioned, offset is the number of bytes to offset from the specified position, and whence is the origin from which to measure the offset. The function returns zero if the operation is successful, and a nonzero value if an error occurs.
The whence argument can be one of the following constants:
- SEEK_SET: The offset is relative to the beginning of the file.
- SEEK_CUR: The offset is relative to the current position in the file.
- SEEK_END: The offset is relative to the end of the file.
When fseek() is called, it sets the file position indicator to the specified position in the file associated with the stream pointer. The offset argument specifies the number of bytes to offset from the origin specified by whence.This function is typically used in programs that need to read or write data from a specific position in a file, such as when searching for a particular piece of data in a large file or when appending data to the end of a file.
Example for fseek():
#include<stdio.h> int main() { FILE *fp; fp = fopen("prepbytes.txt","r"); if(!fp) { printf("Error: File cannot be opened\n"); return 0; } fseek(fp, 4, 0); char ch; while(fread(&ch,sizeof(ch),1,fp)==1) { printf("%c",ch); } fclose(fp); return 0; }
Output:
bytes
Explanation for fseek():
First, let us create a file – prepbytes.txt which contains the data: prepbytes.We can observe that when fseek(fp,4,0) the pointer moves to the 5th byte in the file, or we can say 4 bytes forward from the beginning, So when we traverse the file from that position, we receive output as bytes.
3. rewind():
The rewind() function is a standard library function in C programming language. It is used to set the file position indicator to the beginning of a file, allowing the file to be read from the start again.
Syntax for rewind():
rewind(FILE *fp);
Explanation of Syntax for rewind():
Here, the stream is a pointer to the file stream that needs to be rewound. The function does not return any value. When rewind() is called, it sets the file position indicator to the beginning of the file associated with the stream pointer. Any previous errors or end-of-file conditions are cleared, allowing the file to be read from the start again. This function is typically used in programs that read data from a file multiple times, such as when processing a text file. By rewinding the file to the beginning, the program can read the data again without having to close and reopen the file.
Example for rewind():
#include<stdio.h> int main() { FILE *fp; fp = fopen("prepbytes.txt","r"); if(!fp) { printf("Error in opening file\n"); return 0; } printf("Position of the pointer : %ld\n",ftell(fp)); char ch; while(fread(&ch,sizeof(ch),1,fp)==1) { printf("%c",ch); } printf("Position of the pointer : %ld\n",ftell(fp)); rewind(fp); printf("Position of the pointer : %ld\n",ftell(fp)); fclose(fp); return 0; }
Output:
Position of the pointer : 0
prepbytes
Position of the pointer: 9
Position of the pointer : 0
Explanation of rewind():
First, let us create a file – prepbytes.txt which contains the data: prepbytes. We can observe that firstly when ftell is called, it returns 0 as the position of the pointer is at the beginning, and then after traversing the file, when ftell is called, 9 is returned, which is the size of the file. Now when rewind(fp) is called, the pointer will move to its original position, which is 0. So the last ftell returns 0.
Conclusion
In conclusion, random access is a method of accessing data in a file or storage medium where the data can be retrieved or modified directly at any position, without the need to sequentially read or write through the entire file. Random access provides flexibility and efficiency in managing data, as specific portions of the file can be accessed quickly, regardless of their location. This capability is particularly useful for large files or when frequent random access operations are required.
Frequently Asked Questions (FAQs):
Q1: What is random access?
Random access refers to the ability to access data stored in a file or storage medium directly at any position without the need to traverse the entire file sequentially. It allows for quick retrieval or modification of specific data points within the file.
Q2: How does random access differ from sequential access?
In sequential access, data is accessed in a linear manner, starting from the beginning of the file and progressing sequentially. Random access, on the other hand, enables direct access to any desired position in the file, allowing for more efficient and flexible data retrieval.
Q3: What are the advantages of random access?
Random access provides several advantages, including the ability to quickly access specific data points without reading or writing through the entire file, efficient management of large files, and support for frequent data modification or retrieval operations at any position within the file.
Q4: What are some examples of random access storage devices?
Examples of random access storage devices include hard disk drives (HDDs), solid-state drives (SSDs), and memory cards. These devices allow direct access to data stored at any location without the need to sequentially read or write through the entire storage medium.
Q5: How is random access implemented in programming languages?
Programming languages provide various mechanisms to achieve random access, such as file pointers or seek functions. These features allow programmers to specify the desired position within a file and perform read or write operations at that specific location.
Q6: When is random access particularly useful?
Random access is particularly useful when dealing with large files, databases, or situations where frequent data retrieval or modification operations are required at different positions within the file. It allows for efficient data management and faster access times compared to sequential access methods.