Random Access File in C

The random access file in C are

1. fseek(): 

  • This function is used to move the file pointer from one location of the file to another location of the file.
  • The syntax is fseek(file pointer, offset, position);
  • Where the file pointer specifies the pointer which points to the file that has been opened. 
  • Offset is a long integer that specifies how many positions are to be moved by the file pointer from the current position. The value may be positive or negative. 
  • If it is a positive value it moves in a forward direction. If it is a negative value, it moves in a backward direction.
  • Position specifies the position of the file. The position of the file can be specified by an integer value or symbolic constants.

0, seek.SET 🡪 the beginning of the file.

1, seek.curr 🡪 current position of the file.

2, seek.END 🡪 end of the file.

2. ftell(): 

This function is used to specify the current position of the file pointer. This function returns an integer value. 

The syntax is

 ftell(file pointer);

Ex: ftell(fP);

Rewind: 

This function is used to bring back the file pointer to the beginning of the file. 

The syntax is 

Rewind(file pointer);

Ex: Rewind(fP);

 C Program to reverse the contents of a given file.

#include <stdio.h>
#include <stdlib.h>
int main() {
    FILE *fp, *temp;
    char ch, filename[100];
    long int size, i;
    // Get filename from user
    printf("Enter filename: ");
    scanf("%s", filename);
    // Open file in read mode
    fp = fopen(filename, "r");
    if (fp == NULL) {
        perror("Error opening file");
        exit(1);
    }
    // Get file size
    fseek(fp, 0, SEEK_END); 
    size = ftell(fp);
    // Create temporary file for reversed content
    temp = fopen("temp.txt", "w");
    if (temp == NULL) {
        fclose(fp);
        perror("Error creating temporary file");
        exit(1);
    }
    // Start from the end of the original file
    for (i = size - 1; i >= 0; i--) {
        // Move file pointer to each character from the end
        fseek(fp, i, SEEK_SET); 
        
        // Read the character
        ch = fgetc(fp);
        // Write the character to the temporary file
        fputc(ch, temp);
    }
    // Close both files
    fclose(fp);
    fclose(temp);
    // Remove the original file
    remove(filename);
    // Rename the temporary file to the original filename
    rename("temp.txt", filename);
    printf("File reversed successfully.\n");
    return 0;
}

Output:

Enter filename: helloworld
File reversed successfully.

Line I/O functions of a file

The line I/O functions of a file are fgets() and fputs().

fgets(): This function is used to read a string or a line from the file. 

The syntax is

 fgets(variable, size, file pointer);

Ex: fgets(str, 20,fP);

fgets(str, std, in);

gets(str);

fputs(): This function is used to write a string or line into the file.

The syntax is 

fputs(variable, file pointer);

Ex: fputs(str, fP);

  fputs(str, std, out);

C program to implement fputs and fgets.

#include <stdio.h>
#include <stdlib.h>
#define MAX_LINE_LENGTH 100 
int main() {
    FILE *fp;
    char filename[100], input[MAX_LINE_LENGTH];
    // Get filename from the user
    printf("Enter filename: ");
    scanf("%s", filename);
    // Open file in append mode (create if not exists)
    fp = fopen(filename, "a");
    if (fp == NULL) {
        perror("Error opening file");
        exit(1);
    }
    // Write lines to the file using fputs
    printf("Enter lines (type 'exit' to quit):\n");
    while (1) {
        fgets(input, MAX_LINE_LENGTH, stdin); // Read line from the user
        // Check for exit condition
        if (strncmp(input, "exit", 4) == 0) {
            break;
        }
        fputs(input, fp); // Write line to the file
    }
    fclose(fp); // Close the file
    // Reopen the file in read mode
    fp = fopen(filename, "r");
    if (fp == NULL) {
        perror("Error reopening file");
        exit(1);
    }
    // Read lines from the file using fgets
    printf("\nContents of the file:\n");
    while (fgets(input, MAX_LINE_LENGTH, fp) != NULL) {
        printf("%s", input); // Print each line
    }
    fclose(fp); // Close the file again
    return 0;
}

Output:

Enter filename: helloworld
Enter lines (type 'exit' to quit):
hello my dear
exit
Contents of the file:
..edud uoy era woH !..iH
hello my dear

FAQs of Random Access File in C

Q1. What is a random access file in C, and how does it differ from sequential access?

  • A random access file allows you to directly access any position within the file without reading through it sequentially. 
  • In sequential access, you must read data in the order it was written, starting from the beginning.
  •  Random access is more efficient when you need to modify or retrieve specific data elements within a large file.

Q2. Explain the key functions used for working with random access files in C.

  • fopen: Opens the file in binary mode (e.g., “rb+” for reading and writing).
  • fseek: Moves the file pointer to a specific position within the file based on an offset and origin (e.g., SEEK_SET for the beginning, SEEK_CUR for the current position, SEEK_END for the end).
  • ftell: Tells you the current position of the file pointer.
  • fread: Reads a specified number of bytes from the file into a buffer.
  • fwrite: Writes a specified number of bytes from a buffer into the file.

Q3. How would you update a specific record in a random access file without rewriting the entire file?

  1. Calculate the offset (in bytes) of the record you want to update based on its position and the fixed size of each record.
  2. Use fseek to move the file pointer to that offset.
  3. Use fwrite to overwrite the existing record with the new data.

Q4. What are the advantages and disadvantages of using random access files compared to other file types in C?

Advantages:

  • Efficient access to specific data elements within large files.
  • Ability to update records in place.

Disadvantages:

  • Requires fixed-length records for easy calculation of offsets.
  • Less intuitive for simple sequential reading or writing.

Q5. Can you provide a practical example of where random access files are useful?

Random access files are ideal for:

  • Databases: Storing and retrieving records quickly based on keys.
  • Configuration files: Modifying specific settings without rewriting the whole file.
  • Log files: Jumping to specific timestamps for analysis.
  • Any application where efficient, non-sequential access to data is required.
Scroll to Top