MCS-011 Problem Solving and Programming

Admin | First year, Semester1

Chapters

Newsletter

Sequential vs Random Access Files

In C programming, files can be accessed in two main ways: sequential access and random access. Understanding the difference between these two methods is crucial for efficient file manipulation.

Sequential Access Files

Sequential access means reading or writing data in a file in a linear order, from the beginning to the end. This is the simplest form of file access, where data is processed in the order it is stored.

Characteristics of Sequential Access:

  1. Linear Processing: Data is accessed in a sequence.
  2. Simplicity: Easier to implement and understand.
  3. Efficiency: Efficient for reading/writing large blocks of data.
  4. Use Cases: Log files, simple data logging, streaming data.

Functions for Sequential Access:

  • fscanf, fgets, fgetc: Read data sequentially.
  • fprintf, fputs, fputc: Write data sequentially.

Example:

#include <stdio.h>
int main() { FILE *fp; // Open a file for writing fp = fopen("sequential.txt", "w"); if (fp == NULL) { printf("Error opening file for writing!\n"); return 1; } // Write data sequentially fprintf(fp, "Hello, World!\n"); fprintf(fp, "Sequential file access example.\n"); // Close the file fclose(fp); // Open the file for reading fp = fopen("sequential.txt", "r"); if (fp == NULL) { printf("Error opening file for reading!\n"); return 1; } // Read data sequentially char buffer[100]; while (fgets(buffer, sizeof(buffer), fp) != NULL) { printf("%s", buffer); } // Close the file fclose(fp); return 0; }


Random Access Files

Random access allows reading or writing data at any position in the file without having to process data sequentially from the beginning. This is useful for applications where you need to frequently access different parts of the file.

Characteristics of Random Access:

  1. Direct Access: Jump directly to any location in the file.
  2. Flexibility: More control over file operations.
  3. Efficiency for Large Files: Efficient for accessing large files where only certain parts are needed.
  4. Use Cases: Databases, index files, configuration files.

Functions for Random Access:

  • fseek: Move the file pointer to a specific location.
  • ftell: Get the current position of the file pointer.
  • rewind: Set the file pointer to the beginning of the file.

Example:

#include <stdio.h>
int main() { FILE *fp; // Open a file for writing fp = fopen("random.txt", "w+"); if (fp == NULL) { printf("Error opening file!\n"); return 1; } // Write data at the beginning fprintf(fp, "Random access example.\n"); // Move the file pointer to position 7 (0-based index) fseek(fp, 7, SEEK_SET); // Write data at the new position fprintf(fp, "direct"); // Rewind to the beginning of the file rewind(fp); // Read data to verify the changes char buffer[100]; while (fgets(buffer, sizeof(buffer), fp) != NULL) { printf("%s", buffer); } // Close the file fclose(fp); return 0; }

Choosing between sequential and random access depends on the specific needs of your application and the nature of the data being processed.

File Handling

File handling in C is accomplished using file pointers, which provide a way to access and manipulate files. A file pointer is a variable of type FILE*, used to keep track of the position within the file and manage file operations.


Basic Steps for File Handling

  1. Declare a File Pointer:

    FILE *fp;
  2. Open a File: Use the fopen function to open a file. It returns a file pointer or NULL if the operation fails.

    fp = fopen("filename.txt", "mode");

    Common modes include:

    • "r": Read (file must exist)
    • "w": Write (creates a new file or truncates existing file)
    • "a": Append (writes data to the end of the file)
    • "r+": Read/Write (file must exist)
    • "w+": Read/Write (creates a new file or truncates existing file)
    • "a+": Read/Write (writes data to the end of the file)
  3. Perform File Operations: Use various functions to read from or write to the file.

    • Writing to a File:

      fprintf(fp, "format", data);
      fputc('c', fp); fputs("string", fp);
    • Reading from a File:

      fscanf(fp, "format", &data);
      char c = fgetc(fp); char str[100]; fgets(str, 100, fp);
  4. Close the File: Use fclose to close the file and release resources.

    fclose(fp);

Example

Here's a complete example of writing to and reading from a text file using file pointers.

#include <stdio.h>
int main() { FILE *fp; // Open a file for writing fp = fopen("example.txt", "w"); if (fp == NULL) { printf("Error opening file for writing!\n"); return 1; } // Write to the file fprintf(fp, "Hello, World!\n"); fputs("This is a file handling example.\n", fp); // Close the file fclose(fp); // Open the file for reading fp = fopen("example.txt", "r"); if (fp == NULL) { printf("Error opening file for reading!\n"); return 1; } // Read from the file char buffer[255]; while (fgets(buffer, sizeof(buffer), fp) != NULL) { printf("%s", buffer); } // Close the file fclose(fp); return 0; }

File Operations Summary

  • fopen: Opens a file and returns a file pointer.
  • fclose: Closes a file.
  • fprintf, fputs, fputc: Write data to a file.
  • fscanf, fgets, fgetc: Read data from a file.
  • feof: Checks if the end of the file is reached.
  • ferror: Checks for file operation errors.
  • rewind: Sets the file position to the beginning of the file.
  • ftell: Returns the current file position.
  • fseek: Sets the file position to a specific location.

Using file pointers in C allows efficient and flexible file operations, essential for managing persistent data.

Input and Output using File Pointers

Input and output (I/O) using file pointers in C involve reading from and writing to files. File pointers, of type FILE*, manage the file operations and track the current position within the file. Here’s an explanation of how to perform I/O operations using file pointers:

Opening and Closing Files

Before performing any I/O operations, a file must be opened using fopen, which returns a file pointer. After operations are complete, the file should be closed using fclose to release resources.

#include <stdio.h>
FILE *fp; // Declare a file pointer // Open a file for reading or writing fp = fopen("filename.txt", "mode"); // Close the file fclose(fp);

Writing to a File

Several functions can be used to write data to a file:

  1. fprintf: Formats and writes a string to the file.

    fprintf(fp, "Formatted string: %d\n", 42);
  2. fputs: Writes a string to the file.

    fputs("This is a string.\n", fp);
  3. fputc: Writes a single character to the file.

    fputc('A', fp);

Reading from a File

Several functions can be used to read data from a file:

  1. fscanf: Reads formatted input from the file.

    int num; fscanf(fp, "%d", &num);
  2. fgets: Reads a string from the file until a newline or end-of-file is encountered.

    char buffer[100]; fgets(buffer, 100, fp);
  3. fgetc: Reads a single character from the file.

    char ch; ch = fgetc(fp);

Example: Writing and Reading a File

Here’s a complete example demonstrating writing to and reading from a file using the functions mentioned above.

#include <stdio.h>
int main() { FILE *fp; // Open a file for writing fp = fopen("example.txt", "w"); if (fp == NULL) { printf("Error opening file for writing!\n"); return 1; } // Write to the file fprintf(fp, "Hello, World!\n"); fputs("This is a file handling example.\n", fp); fputc('A', fp); // Close the file fclose(fp); // Open the file for reading fp = fopen("example.txt", "r"); if (fp == NULL) { printf("Error opening file for reading!\n"); return 1; } // Read from the file using fscanf char str[50]; fscanf(fp, "%s", str); printf("Read using fscanf: %s\n", str); // Read from the file using fgets fgets(str, 50, fp); printf("Read using fgets: %s", str); // Read from the file using fgetc char ch; ch = fgetc(fp); printf("Read using fgetc: %c\n", ch); // Close the file fclose(fp); return 0; }

File Positioning

Sometimes, you may need to control the file pointer position using functions like fseek, ftell, and rewind.

  • fseek: Sets the file position to a specific location.

    fseek(fp, offset, origin); // origin can be SEEK_SET, SEEK_CUR, or SEEK_END
  • ftell: Returns the current file position.

    long pos = ftell(fp);
  • rewind: Sets the file position to the beginning of the file.

    rewind(fp);

Error Handling

Always check the return values of file operations to handle errors gracefully.

  • ferror: Checks if a file error occurred.

    if (ferror(fp)) {
    printf("Error reading from the file.\n"); }
  • feof: Checks if the end of the file is reached.

    if (feof(fp)) {     printf("End of file reached.\n"); }

Using these functions and techniques, you can efficiently perform input and output operations using file pointers in C.

Sequential vs Random Access Files

In C programming, files can be accessed in two main ways: sequential access and random access. Understanding the difference between these two methods is crucial for efficient file manipulation.

Sequential Access Files

Sequential access means reading or writing data in a file in a linear order, from the beginning to the end. This is the simplest form of file access, where data is processed in the order it is stored.

Characteristics of Sequential Access:

  1. Linear Processing: Data is accessed in a sequence.
  2. Simplicity: Easier to implement and understand.
  3. Efficiency: Efficient for reading/writing large blocks of data.
  4. Use Cases: Log files, simple data logging, streaming data.

Functions for Sequential Access:

  • fscanf, fgets, fgetc: Read data sequentially.
  • fprintf, fputs, fputc: Write data sequentially.

Example:

#include <stdio.h>
int main() { FILE *fp; // Open a file for writing fp = fopen("sequential.txt", "w"); if (fp == NULL) { printf("Error opening file for writing!\n"); return 1; } // Write data sequentially fprintf(fp, "Hello, World!\n"); fprintf(fp, "Sequential file access example.\n"); // Close the file fclose(fp); // Open the file for reading fp = fopen("sequential.txt", "r"); if (fp == NULL) { printf("Error opening file for reading!\n"); return 1; } // Read data sequentially char buffer[100]; while (fgets(buffer, sizeof(buffer), fp) != NULL) { printf("%s", buffer); } // Close the file fclose(fp); return 0; }


Random Access Files

Random access allows reading or writing data at any position in the file without having to process data sequentially from the beginning. This is useful for applications where you need to frequently access different parts of the file.

Characteristics of Random Access:

  1. Direct Access: Jump directly to any location in the file.
  2. Flexibility: More control over file operations.
  3. Efficiency for Large Files: Efficient for accessing large files where only certain parts are needed.
  4. Use Cases: Databases, index files, configuration files.

Functions for Random Access:

  • fseek: Move the file pointer to a specific location.
  • ftell: Get the current position of the file pointer.
  • rewind: Set the file pointer to the beginning of the file.

Example:

#include <stdio.h>
int main() { FILE *fp; // Open a file for writing fp = fopen("random.txt", "w+"); if (fp == NULL) { printf("Error opening file!\n"); return 1; } // Write data at the beginning fprintf(fp, "Random access example.\n"); // Move the file pointer to position 7 (0-based index) fseek(fp, 7, SEEK_SET); // Write data at the new position fprintf(fp, "direct"); // Rewind to the beginning of the file rewind(fp); // Read data to verify the changes char buffer[100]; while (fgets(buffer, sizeof(buffer), fp) != NULL) { printf("%s", buffer); } // Close the file fclose(fp); return 0; }

Choosing between sequential and random access depends on the specific needs of your application and the nature of the data being processed.

The Unbuffered I/O - The Unix like File Routine

Unbuffered I/O in C, often associated with UNIX-like file routines, refers to direct communication with the underlying file system without using any intermediate buffering. This can lead to more immediate read and write operations but can also be less efficient for certain tasks compared to buffered I/O.

Characteristics of Unbuffered I/O

  1. Direct Interaction: I/O operations interact directly with the file system, bypassing any intermediate buffering.
  2. Immediate Effect: Data is immediately read from or written to the file without being stored in an intermediate buffer.
  3. Lower Overhead: Reduced overhead as there is no buffer management.
  4. Potential Inefficiency: Can be less efficient for small, frequent I/O operations because each operation directly accesses the file system.

Common UNIX-like File Routines

The UNIX-like file routines for unbuffered I/O include open, read, write, lseek, and close.

1. open

Opens a file and returns a file descriptor, which is an integer representing the open file.

#include <fcntl.h>
#include <unistd.h> int fd = open("filename.txt", O_RDONLY); // Open for reading if (fd == -1) { // Handle error }

Common flags for open:

  • O_RDONLY: Open for reading
  • O_WRONLY: Open for writing
  • O_RDWR: Open for reading and writing
  • O_CREAT: Create the file if it does not exist
  • O_TRUNC: Truncate the file to zero length
  • O_APPEND: Append to the file

2. read

Reads data from an open file into a buffer.

ssize_t bytesRead;
char buffer[100]; bytesRead = read(fd, buffer, sizeof(buffer)); if (bytesRead == -1) { // Handle error }

3. write

Writes data from a buffer to an open file.

ssize_t bytesWritten;
const char *data = "Hello, World!"; bytesWritten = write(fd, data, strlen(data)); if (bytesWritten == -1) { // Handle error }

4. lseek

Moves the file pointer to a specified location in the file.

off_t newPos = lseek(fd, offset, SEEK_SET); // Move to 'offset' from the beginning
if (newPos == (off_t)-1) { // Handle error }

Seek constants:

  • SEEK_SET: From the beginning of the file
  • SEEK_CUR: From the current position
  • SEEK_END: From the end of the file

5. close

Closes an open file descriptor.

if (close(fd) == -1) {
// Handle error }

Example

Here is a complete example demonstrating unbuffered I/O operations:

#include <fcntl.h>
#include <unistd.h> #include <stdio.h> #include <string.h> int main() { int fd; ssize_t bytesRead, bytesWritten; char buffer[100]; // Open a file for writing (create if it doesn't exist) fd = open("unbuffered.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644); if (fd == -1) { perror("Error opening file for writing"); return 1; } // Write data to the file const char *data = "Unbuffered I/O example.\n"; bytesWritten = write(fd, data, strlen(data)); if (bytesWritten == -1) { perror("Error writing to file"); close(fd); return 1; } // Close the file if (close(fd) == -1) { perror("Error closing file"); return 1; } // Open the file for reading fd = open("unbuffered.txt", O_RDONLY); if (fd == -1) { perror("Error opening file for reading"); return 1; } // Read data from the file bytesRead = read(fd, buffer, sizeof(buffer) - 1); if (bytesRead == -1) { perror("Error reading from file"); close(fd); return 1; } // Null-terminate the buffer and print it buffer[bytesRead] = '\0'; printf("Read from file:\n%s", buffer); // Close the file if (close(fd) == -1) { perror("Error closing file"); return 1; } return 0; }

Unbuffered I/O in UNIX-like systems provides a direct and immediate method for performing file operations. While this can be beneficial for certain use cases where immediate data consistency is critical, it can also introduce inefficiencies for applications that perform frequent small I/O operations due to the lack of buffering. Understanding when to use unbuffered I/O versus buffered I/O is crucial for optimizing file I/O performance in C programs.

About John Doe

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Report an issue

Related Posts

3 Comments

John Doe

5 min ago

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Reply

John Doe

5 min ago

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Reply