C Programs Tutorials | IT Developer
IT Developer

C Programming - C File I/O (File Handling)



Share with a Friend

C Programming - C File I/O (File Handling)

File I/O (File Handling) in C

In C, File I/O (Input/Output) refers to the process of reading data from files and writing data to files. The C standard library provides a set of functions for performing file operations. These functions are declared in the <stdio.h> header file and allow for both text and binary file handling.

Opening and Closing Files

Before reading or writing to a file, it must be opened using the fopen() function. After the operations are complete, the file must be closed using the fclose() function.

  1. Opening a File (fopen())

The fopen() function opens a file and returns a pointer to a FILE object. The FILE pointer is then used for subsequent operations like reading or writing to the file.

Syntax:

C

FILE *fopen(const char *filename, const char *mode);

    • filename: The name of the file to be opened (with or without path).
    • mode: The mode in which the file is to be opened. Common modes are:
      • "r": Read mode. Opens a file for reading.
      • "w": Write mode. Creates a new file for writing. If the file already exists, it is overwritten.
      • "a": Append mode. Opens a file for appending at the end.
      • "r+": Read and write mode. Opens a file for both reading and writing.
      • "w+": Read and write mode. Creates a file if it doesn't exist and overwrites if it does.
      • "a+": Read and append mode. Opens for reading and appending.
  1. Closing a File (fclose())

After performing file operations, it is essential to close the file using the fclose() function. This ensures that resources are freed up and the file is saved properly.

Syntax:

C

int fclose(FILE *stream);

    • stream: The FILE pointer returned by fopen().

Example:

C

FILE *file = fopen("data.txt", "w");

if (file == NULL) {

    printf("Error opening file.\n");

} else {

    printf("File opened successfully.\n");

    fclose(file);

}

Reading from a File

  1. fgetc() - Reads a single character from the file.

Syntax:

C

int fgetc(FILE *stream);

    • stream: The pointer to the file from which to read.
    • Returns the character read as an unsigned char cast to an int, or EOF if the end of the file is reached.

Example:

C

FILE *file = fopen("data.txt", "r");

char ch;

if (file != NULL) {

    while ((ch = fgetc(file)) != EOF) {

        putchar(ch);  // Prints each character from the file

    }

    fclose(file);

}

  1. fgets() - Reads a line of text from the file.

Syntax:

C

char *fgets(char *str, int n, FILE *stream);

    • str: Pointer to the character array where the input will be stored.
    • n: The maximum number of characters to read (including the null terminator).
    • stream: The pointer to the file from which to read.
    • Returns the string read from the file (including the newline character) or NULL on error or end of file.

Example:

C

FILE *file = fopen("data.txt", "r");

char line[100];

if (file != NULL) {

    while (fgets(line, sizeof(line), file)) {

        printf("%s", line);  // Prints each line from the file

    }

    fclose(file);

}

  1. fscanf() - Reads formatted input from a file.

Syntax:

C

int fscanf(FILE *stream, const char *format, ...);

    • stream: The file pointer to read from.
    • format: A format string containing format specifiers like %d, %f, %s, etc.
    • Returns the number of items successfully read.

Example:

C

FILE *file = fopen("data.txt", "r");

int num;

if (file != NULL) {

    fscanf(file, "%d", &num);  // Reads an integer from the file

    printf("Read integer: %d\n", num);

    fclose(file);

}

Writing to a File

  1. fputc() - Writes a single character to a file.

Syntax:

C

int fputc(int character, FILE *stream);

    • character: The character to write.
    • stream: The pointer to the file to write to.
    • Returns the character written as an unsigned char cast to an int, or EOF on error.

Example:

C

FILE *file = fopen("data.txt", "w");

if (file != NULL) {

    fputc('A', file);  // Writes character 'A' to the file

    fclose(file);

}

  1. fputs() - Writes a string to a file.

Syntax:

C

int fputs(const char *str, FILE *stream);

    • str: The string to write to the file.
    • stream: The pointer to the file to write to.
    • Returns a non-negative number on success, EOF on error.

Example:

C

FILE *file = fopen("data.txt", "w");

if (file != NULL) {

    fputs("Hello, File!", file);  // Writes the string to the file

    fclose(file);

}

  1. fprintf() - Writes formatted output to a file.

Syntax:

C

int fprintf(FILE *stream, const char *format, ...);

    • stream: The file pointer to write to.
    • format: A format string containing format specifiers (e.g., %d, %f).
    • Returns the number of characters written, or a negative value on error.

Example:

C

FILE *file = fopen("data.txt", "w");

if (file != NULL) {

    fprintf(file, "Name: %s, Age: %d\n", "John", 25);  // Writes formatted data

    fclose(file);

}

Binary File Handling

Binary file operations are similar to text file operations, but binary files allow the storage of data in a binary format. This is useful for non-text data (e.g., images, audio, or custom data formats).

  1. Opening a Binary File ("rb", "wb", "rb+", "wb+")
    • "rb": Open for reading binary.
    • "wb": Open for writing binary.
    • "rb+": Open for both reading and writing binary.
    • "wb+": Open for both reading and writing binary (creates a new file).
  2. Reading from a Binary File

Use fread() to read data from a binary file.

Syntax:

C

size_t fread(void *ptr, size_t size, size_t count, FILE *stream);

    • ptr: Pointer to the memory block where data will be stored.
    • size: Size of each element to read.
    • count: Number of elements to read.
    • stream: The file pointer.

Example:

C

FILE *file = fopen("data.bin", "rb");

int num;

if (file != NULL) {

    fread(&num, sizeof(int), 1, file);  // Reads an integer from the binary file

    printf("Number from binary file: %d\n", num);

    fclose(file);

}

  1. Writing to a Binary File

Use fwrite() to write data to a binary file.

Syntax:

C

size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);

    • ptr: Pointer to the memory block containing data to write.
    • size: Size of each element to write.
    • count: Number of elements to write.
    • stream: The file pointer.

Example:

C

FILE *file = fopen("data.bin", "wb");

int num = 42;

if (file != NULL) {

    fwrite(&num, sizeof(int), 1, file);  // Writes an integer to the binary file

    fclose(file);

}

File Positioning

  1. fseek() - Moves the file pointer to a specific location.

Syntax:

C

int fseek(FILE *stream, long int offset, int origin);

    • offset: The number of bytes to move.
    • origin: The starting point. It can be SEEK_SET, SEEK_CUR, or SEEK_END.
  1. ftell() - Returns the current position of the file pointer.

Syntax:

C

long int ftell(FILE *stream);

  1. rewind() - Resets the file pointer to the beginning of the file.

Syntax:

C

void rewind(FILE *stream);

Conclusion

File handling in C is an essential feature for persistent storage. Using the standard I/O functions (fopen(), fclose(), fread(), fwrite(), etc.), you can read from and write to both text and binary files. It's crucial to open files in the appropriate mode, perform file operations efficiently, and close files when done to prevent resource leaks.