ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCC-112File Processing Stream…
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CC-112

    Programming Fundamentals

    Progress0 / 39 done
    Topics39
    1Introduction to Problem Solving, Algorithms, Programming, and C Language2Problem Solving, a brief review of Von-Neumann Architecture3The C Programming Language, Pseudo-code, Concept of Variable4Data types in Pseudo-code, The C Standard Library and Open Source5Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6Concept of Integer division, Flowchart and its notations7Typical C Program Development Environment, Role of Compiler and Linker8Test Driving C Application
    9A Simple C Program: Printing Text, Adding Two Integer10Memory Concepts, Arithmetic in C, Operators
    11Equality and Relational Operators
    12The if, if...else, while Nested Control Statements
    13for, switch, do...while, break, continue, Logical Operators
    14Modularizing Program in C, Math Library Functions15Function Definitions and Prototypes, Function-Call Stack and Stack Frames16Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration
    18Defining Arrays, Character Arrays, Static and Automatic Local Arrays19Passing Arrays to Function, Sorting and Searching Arrays20Multidimensional and Variable Length Arrays
    21Pointer Definitions and Initialization, Pointer Operators22Passing Arguments to Function by Reference, Using the const and sizeof Operator23Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24Function Pointers
    25Strings and Characters, Character Handling Library26String Functions, Library Functions
    27Streams, Formatted Output with printf, Formatted Input with scanf
    28Defining Structures, Accessing Structure Member, Structures and Functions29typedef, Unions
    30Bitwise Operators, Bit Fields, Enumeration Constants
    31Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File
    32#include, #define, Conditional Compilation, #error and #pragma33# and ## Operators, Predefined Symbolic Constants, Assertions
    34Variable Length Argument List, Using Command Line Arguments35Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36Suffixes for Integer and Floating-Point Literals, Signal Handling
    37calloc and realloc, goto
    38Self-Referential Structures, Linked Lists39Efficiency of Algorithms, Selection and Insertion Sort
    8 min read
    Topic 31 of 39
    Topic Study Note Illustration
    31

    File Processing: Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File

    In C, file processing allows you to store and manipulate data outside of the program's memory. Files are an essential component of most applications, as they provide...

    File Processing in C: Files and Streams, Sequential vs. Random-Access File Handling

    In C, file processing allows you to store and manipulate data outside of the program's memory. Files are an essential component of most applications, as they provide a way to save data between program executions. File handling in C is done using streams, and the operations you perform on files depend on the type of file—sequential or random-access.


    1. Files and Streams in C

    In C, files are handled as streams. A stream is a flow of data between your program and a file. There are two types of streams:

    • Input stream: For reading data from a file.
    • Output stream: For writing data to a file.

    A file in C is represented by a FILE pointer, which is used by various functions from the stdio.h library to open, read, write, and close files.

    Common File Operations:

    • Opening a File: To work with a file, you first need to open it using the fopen() function.
    • Reading and Writing: Data can be read or written using functions like fread(), fwrite(), fscanf(), and fprintf().
    • Closing a File: Always close a file after you are done using it, using the fclose() function.

    File Modes:

    When opening a file with fopen(), you must specify the mode in which the file will be used. The most common modes are:

    • "r": Open for reading (file must exist).
    • "w": Open for writing (creates a new file or truncates an existing file).
    • "a": Open for appending (create a new file or add to the end of an existing file).
    • "rb", "wb", "ab": Same as the above, but for binary files.
    • "r+": Open for both reading and writing.
    • "w+": Open for both reading and writing (creates a new file or truncates an existing one).
    • "a+": Open for reading and appending (creates a new file or appends to the end).

    2. Creating, Reading, and Writing to a Sequential File

    In sequential files, data is written or read in a linear fashion, one record after another. Each read or write operation starts from the beginning and goes forward in the file.

    Example: Creating and Writing to a Sequential File

    #include <stdio.h>
    
    int main() {
        FILE *file = fopen("example.txt", "w"); // Open file in write mode
        if (file == NULL) {
            printf("Unable to open file.\n");
            return 1;
        }
    
        fprintf(file, "Hello, world!\n"); // Write a string to the file
        fprintf(file, "This is a sequential file example.\n");
    
        fclose(file); // Close the file
        printf("File written successfully.\n");
    
        return 0;
    }
    

    Explanation:

    • fopen("example.txt", "w"): Opens a file for writing. If it doesn’t exist, it will be created.
    • fprintf(): Writes formatted data (like printf()) to the file.
    • fclose(): Closes the file after the operation is complete.

    Reading from a Sequential File

    #include <stdio.h>
    
    int main() {
        FILE *file = fopen("example.txt", "r"); // Open file in read mode
        if (file == NULL) {
            printf("Unable to open file.\n");
            return 1;
        }
    
        char line[100];
        while (fgets(line, sizeof(line), file)) { // Read one line at a time
            printf("%s", line); // Print each line from the file
        }
    
        fclose(file); // Close the file
        return 0;
    }
    

    Explanation:

    • fopen("example.txt", "r"): Opens the file for reading.
    • fgets(): Reads a line from the file into the line buffer.
    • The while loop continues reading lines from the file until it reaches the end.

    Output:

    Hello, world!
    This is a sequential file example.
    

    3. Random-Access Files

    A random-access file allows you to move the file pointer to any position in the file and read or write data from that specific location. This is especially useful when dealing with large data sets or when you need to access individual records at specific positions in the file without reading the entire file sequentially.

    To work with random-access files, you typically use fseek(), ftell(), and fread()/fwrite().

    File Operations for Random-Access Files:

    • fseek(FILE *stream, long offset, int whence): Moves the file pointer to a specified location.
      • offset: The number of bytes to move the pointer.
      • whence: The reference point (e.g., SEEK_SET for the beginning, SEEK_CUR for current position, SEEK_END for the end).
    • ftell(FILE *stream): Returns the current position of the file pointer.
    • fread() and fwrite(): Read and write blocks of data from or to a file at the current pointer position.

    Example: Writing and Reading from a Random-Access File

    #include <stdio.h>
    
    struct Student {
        int id;
        char name[50];
    };
    
    int main() {
        FILE *file = fopen("students.dat", "wb+"); // Open in binary read-write mode
        if (file == NULL) {
            printf("Unable to open file.\n");
            return 1;
        }
    
        struct Student s1 = {1, "Alice"};
        struct Student s2 = {2, "Bob"};
    
        // Writing to the file
        fwrite(&s1, sizeof(struct Student), 1, file); // Write s1 to the file
        fwrite(&s2, sizeof(struct Student), 1, file); // Write s2 to the file
    
        // Move the file pointer to the beginning
        fseek(file, 0, SEEK_SET);
    
        // Reading from the file
        struct Student s3, s4;
        fread(&s3, sizeof(struct Student), 1, file); // Read the first student
        fread(&s4, sizeof(struct Student), 1, file); // Read the second student
    
        printf("Student 1: %d, %s\n", s3.id, s3.name);
        printf("Student 2: %d, %s\n", s4.id, s4.name);
    
        fclose(file); // Close the file
        return 0;
    }
    

    Explanation:

    • We define a structure Student with an integer id and a name.
    • fwrite() is used to write the Student structure to the file in binary mode.
    • fseek() moves the file pointer back to the beginning of the file so we can read the data we just wrote.
    • fread() is used to read the structures from the file at the current file pointer position.

    Output:

    Student 1: 1, Alice
    Student 2: 2, Bob
    

    4. Handling Binary Files

    Binary files store data in the same format as it is in memory, unlike text files, which store data as human-readable characters. You use binary mode ("wb", "rb", etc.) to read and write binary files.

    Example: Writing to a Binary File

    #include <stdio.h>
    
    int main() {
        FILE *file = fopen("data.bin", "wb"); // Open in binary write mode
        if (file == NULL) {
            printf("Unable to open file.\n");
            return 1;
        }
    
        int numbers[] = {1, 2, 3, 4, 5};
        fwrite(numbers, sizeof(int), 5, file); // Write array to binary file
    
        fclose(file);
        return 0;
    }
    

    Example: Reading from a Binary File

    #include <stdio.h>
    
    int main() {
        FILE *file = fopen("data.bin", "rb"); // Open in binary read mode
        if (file == NULL) {
            printf("Unable to open file.\n");
            return 1;
        }
    
        int numbers[5];
        fread(numbers, sizeof(int), 5, file); // Read array from binary file
    
        for (int i = 0; i < 5; i++) {
            printf("%d ", numbers[i]);
        }
    
        fclose(file);
        return 0;
    }
    

    Output:

    1 2 3 4 5
    

    5. Conclusion

    File processing in C allows you to store and manipulate large datasets efficiently. The operations for file handling can be divided into two categories based on the type of file:

    1. Sequential Files: Data is read or written one record at a time in a linear fashion.
    2. Random-Access Files: Allows the program to access data at any position within the file using file pointers.

    By using functions like fopen(), fread(), fwrite(), fseek(), and ftell(), you can perform a variety of file operations, ranging from simple text-based file reading to more complex binary file manipulation.

    ← Previous topic 30
    Bit Manipulation and Enumeration: Bitwise Operators, Bit Fields, Enumeration Constants
    Next topic 32 →
    Preprocessor: #include, #define, Conditional Compilation, #error and #pragma

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    8mremaining
    1.4kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Programming Fundamentals