File - I/O

C Programming Tutorial: File I/O

Welcome to the Codes With Pankaj "File Input and Output (I/O) in C Programming" tutorial! This tutorial will guide you through the concepts and practical applications of file I/O operations in C.

Table of Contents


1. Introduction to File I/O

File input and output (I/O) operations in C allow programs to read from and write to external files. This is essential for tasks such as reading configuration files, processing data stored in files, and storing program output.

2. Opening and Closing Files

fopen Function

The fopen function is used to open files and returns a file pointer to the opened file. It takes two parameters: the file path and the mode.

Example:

#include <stdio.h>

int main() {
    FILE *fp;
    fp = fopen("p4n.txt", "r");
    if (fp == NULL) {
        printf("File could not be opened.\n");
        return 1;
    }
    fclose(fp);
    return 0;
}

3. Reading from Files

fscanf Function

The fscanf function is used to read formatted input from a file. It is similar to scanf but reads from a file instead of the standard input.

Example:

#include <stdio.h>

int main() {
    FILE *fp;
    int num;
    fp = fopen("p4n.txt", "r");
    fscanf(fp, "%d", &num);
    printf("Number read from file: %d\n", num);
    fclose(fp);
    return 0;
}

4. Writing to Files

fprintf Function

The fprintf function is used to write formatted output to a file. It is similar to printf but writes to a file instead of the standard output.

Example:

#include <stdio.h>

int main() {
    FILE *fp;
    int num = 10;
    fp = fopen("p4n.txt", "w");
    fprintf(fp, "Number: %d\n", num);
    fclose(fp);
    return 0;
}

5. File Positioning

fseek and ftell Functions

The fseek function is used to move the file pointer to a specified position within the file. The ftell function returns the current position of the file pointer.

Example:

#include <stdio.h>

int main() {
    FILE *fp;
    fp = fopen("p4n.txt", "r");
    fseek(fp, 0, SEEK_END); // Move to end of file
    printf("File size: %ld bytes\n", ftell(fp));
    fclose(fp);
    return 0;
}

6. Error Handling in File I/O

Error handling is crucial in file I/O operations to handle cases where operations fail due to various reasons such as file not found, insufficient permissions, etc.

Example:

#include <stdio.h>

int main() {
    FILE *fp;
    fp = fopen("nonexistent_p4n.txt", "r");
    if (fp == NULL) {
        perror("Error");
        return 1;
    }
    fclose(fp);
    return 0;
}

7. Common Mistakes and Best Practices

Common Mistakes

  1. Not Checking Return Values: Always check the return values of file I/O functions for errors.

  2. Leaving Files Open: Always close files after reading from or writing to them to avoid resource leaks.

  3. Incorrect File Modes: Ensure that the file modes ("r", "w", "a", etc.) are used correctly.

Best Practices

  1. Error Checking: Always check for errors after performing file I/O operations.

  2. Close Files Properly: Always close files after using them to free up system resources.

  3. Use Buffered I/O: Buffered I/O operations are generally faster than unbuffered ones.

8. Exercises

Try these exercises to practice file I/O in C:

  1. Exercise 1: Write a program to read and print the contents of a text file.

  2. Exercise 2: Write a program to copy the contents of one text file into another text file.

  3. Exercise 3: Write a program to append a line to an existing text file.

  4. Exercise 4: Write a program to read integers from a file and print their sum.

  5. Exercise 5: Write a program to count the number of lines, words, and characters in a text file.


We hope this tutorial has helped you understand file input and output (I/O) operations in C programming. Practice with the exercises provided to reinforce your understanding. Happy coding!

For more tutorials, visit www.codeswithpankaj.com.

Last updated