ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Programming Fundamentals
    CC-112
    Progress0 / 39 topics
    Topics
    1. Introduction to Problem Solving, Algorithms, Programming, and C Language2. Problem Solving, a brief review of Von-Neumann Architecture3. The C Programming Language, Pseudo-code, Concept of Variable4. Data types in Pseudo-code, The C Standard Library and Open Source5. Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6. Concept of Integer division, Flowchart and its notations7. Typical C Program Development Environment, Role of Compiler and Linker8. Test Driving C Application9. Introduction to C Programming: A Simple C Program: Printing Text, Adding Two Integer10. Memory Concepts, Arithmetic in C, Operators11. Decision Making: Equality and Relational Operators12. Structured Program Development: The if, if...else, while Nested Control Statements13. Program Control: for, switch, do...while, break, continue, Logical Operators14. Functions: Modularizing Program in C, Math Library Functions15. Function Definitions and Prototypes, Function-Call Stack and Stack Frames16. Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17. Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration18. Arrays: Defining Arrays, Character Arrays, Static and Automatic Local Arrays19. Passing Arrays to Function, Sorting and Searching Arrays20. Multidimensional and Variable Length Arrays21. Pointers: Pointer Definitions and Initialization, Pointer Operators22. Passing Arguments to Function by Reference, Using the const and sizeof Operator23. Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24. Function Pointers25. Characters and Strings: Strings and Characters, Character Handling Library26. String Functions, Library Functions27. Formatted Input/Output: Streams, Formatted Output with printf, Formatted Input with scanf28. Structures: Defining Structures, Accessing Structure Member, Structures and Functions29. typedef, Unions30. Bit Manipulation and Enumeration: Bitwise Operators, Bit Fields, Enumeration Constants31. File Processing: Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File32. Preprocessor: #include, #define, Conditional Compilation, #error and #pragma33. # and ## Operators, Predefined Symbolic Constants, Assertions34. Other Topics: Variable Length Argument List, Using Command Line Arguments35. Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36. Suffixes for Integer and Floating-Point Literals, Signal Handling37. Dynamic Memory Allocation: calloc and realloc, goto38. Advance Topics: Self-Referential Structures, Linked Lists39. Efficiency of Algorithms, Selection and Insertion Sort
    CC-112›File Processing: Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File
    Programming FundamentalsTopic 31 of 39

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

    8 minread
    1,354words
    Intermediatelevel

    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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time8 min
      Word count1,354
      Code examples0
      DifficultyIntermediate