C language content

File handling in C allows you to perform operations like creating, reading, writing, and closing files. The C Standard Library provides several functions to handle files efficiently. Here’s a detailed explanation of some of the most commonly used functions: ‘fopen‘, ‘fclose‘, ‘fread‘, ‘fwrite‘, ‘fprintf‘, and ‘fscanf‘.

1. fopen

The ‘fopen‘ function is used to open a file. It returns a pointer to a ‘FILE‘ object that represents the file. The syntax is:

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

				
			
  • filename: A string that contains the name of the file to be opened.
  • mode: A string that specifies the file access mode (e.g., read, write, append).

Common modes include:

  • "r": Open for reading. The file must exist.
  • "w": Open for writing. If the file exists, it will be truncated to zero length; if it does not exist, it will be created.
  • "a": Open for appending. Writes data at the end of the file. The file is created if it does not exist.
  • "r+": Open for both reading and writing. The file must exist.
  • "w+": Open for both reading and writing. If the file exists, it will be truncated; if it does not exist, it will be created.
  • "a+": Open for both reading and appending. The file is created if it does not exist.

Example:

				
					FILE *fp = fopen("example.txt", "r");
if (fp == NULL) {
    perror("Error opening file");
}

				
			

2. fclose

The ‘fclose‘ function is used to close a file opened by ‘fopen‘. The syntax is:

				
					int fclose(FILE *stream);

				
			
  • stream: A pointer to the FILE object that represents the open file.

Returns 0 if successful, or EOF if an error occurs.

Example:

				
					if (fclose(fp) != 0) {
    perror("Error closing file");
}

				
			

3. fread

The ‘fread‘ function reads data from a file. The syntax is:

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

				
			
  • ptr: Pointer to a buffer where the read data will be stored.
  • size: Size in bytes of each element to be read.
  • nmemb: Number of elements to be read.
  • stream: Pointer to the FILE object.

Returns the number of elements successfully read.

Example:

				
					char buffer[100];
size_t n = fread(buffer, sizeof(char), 100, fp);
if (n != 100 && ferror(fp)) {
    perror("Error reading file");
}

				
			

4. fwrite

The ‘fwrite‘ function writes data to a file. The syntax is:

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

				
			
  • ptr: Pointer to the data to be written.
  • size: Size in bytes of each element to be written.
  • nmemb: Number of elements to be written.
  • stream: Pointer to the FILE object.

Returns the number of elements successfully written.

Example:

				
					const char *data = "Hello, World!";
size_t n = fwrite(data, sizeof(char), strlen(data), fp);
if (n != strlen(data)) {
    perror("Error writing file");
}

				
			

5. fprintf

The ‘fprintf‘ function writes formatted output to a file. The syntax is:

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

				
			
  • stream: Pointer to the FILE object.
  • format: A string that specifies the format of the output, similar to printf.

Returns the number of characters written, or a negative value if an error occurs.

Example:

				
					int age = 25;
fprintf(fp, "Age: %d\n", age);

				
			

6. fscanf

The ‘fscanf‘ function reads formatted input from a file. The syntax is:

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

				
			
  • stream‘: Pointer to the ‘FILE‘ object.
  • format‘: A string that specifies the format of the input, similar to ‘scanf‘.

Returns the number of input items successfully matched and assigned.

Example:

				
					int age;
fscanf(fp, "%d", &age);

				
			

Example Program

Here’s a complete example demonstrating these functions:

				
					#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *fp;
    char buffer[100];
    
    // Open a file for writing
    fp = fopen("example.txt", "w");
    if (fp == NULL) {
        perror("Error opening file for writing");
        return EXIT_FAILURE;
    }
    
    // Write to the file
    fprintf(fp, "Hello, World!\n");
    fclose(fp);
    
    // Open the file for reading
    fp = fopen("example.txt", "r");
    if (fp == NULL) {
        perror("Error opening file for reading");
        return EXIT_FAILURE;
    }
    
    // Read from the file
    if (fgets(buffer, sizeof(buffer), fp) != NULL) {
        printf("Read from file: %s", buffer);
    } else {
        perror("Error reading from file");
    }
    
    fclose(fp);
    return EXIT_SUCCESS;
}

				
			

This program writes “Hello, World!” to a file and then reads it back, displaying the content on the console.

Scroll to Top