File Handling in C Language Examples: A Complete Guide

Last update: December 1th 2025
  • File handling in C allows persistent reading and writing, essential for storing data beyond the execution of the program.
  • Opening modes (text vs binary) influence end-of-line handling and the reading/writing of non-textual data.
  • Standard functions (fopen, fprintf, fgets, fread, fwrite, fclose) facilitate the handling of files and structures, including binary files.
  • Precautions: Use correct modes to avoid data loss, close files after use, and consider libraries for handling Unicode.
File Management in C Language

In the world of programming, file handling is a fundamental skill that every developer must master. When it comes to C language, file handling becomes even more relevant due to its focus on direct manipulation of files in the operating system. In this article, we will explore file handling in detail in C language, providing practical and useful examples to help you understand and master this important area of ​​development.

What is file handling in C language?

File handling in C language refers to the ability to read and write data to files from a program written in this language. Through file handling, you can create, open, close, read and write to files, allowing you to store and retrieve information persistently.

File management in C language It is especially useful when you need to store data beyond the duration of the program's execution. You can save information to files for future use or for sharing. data with other programs.

Importance of file management in C language

File management is a essential skill for developers software, as it allows them to interact with data external to the program. By using file handling in C language, you can read input data from a file, process it, and output results in another file. This is especially useful in applications that handle large volumes of information or need to store data for later use.

File handling in C language is also crucial for the development of database systems, compilers and any program that requires persistent information storage.

Advantages of file handling in C language

File handling in C language offers several important advantages:

  1. Data persistence: Archives allow data to persist beyond the lifetime of a program, meaning it can be accessed during future executions.
  2. Big data storage: File handling is especially useful when working with large volumes of information that do not fit in main memory.
  3. Sharing information between programs: Storing data in files facilitates the exchange of information between different programs, even those written in different languages.
  4. Data organization: Files allow data to be organized into specific structures, making it easier to read and write.
  5. Data recovery: In case of program failures or interruptions, data stored in files can be recovered and restored.

file handling in c language examples

Next, we will explore some practical examples of file handling in C language to illustrate how the different functions and operations are used.

Example 1: Create a file and write data to it

#include <stdio.h>  // Incluye la biblioteca estándar de entrada/salida

int main() {
    // Declara un puntero a FILE para manejar el archivo
    FILE *archivo;

    // Intenta abrir (o crear) el archivo "datos.txt" en modo escritura
    archivo = fopen("datos.txt", "w");

    // Verifica si el archivo se abrió correctamente
    if (archivo == NULL) {
        // Si hubo un error, imprime un mensaje y termina el programa
        printf("No se pudo crear el archivo.");
        return 1;  // Retorna 1 para indicar que hubo un error
    }

    // Escribe la cadena "¡Hola, mundo!" en el archivo
    fprintf(archivo, "¡Hola, mundo!");

    // Cierra el archivo
    fclose(archivo);

    // Termina el programa exitosamente
    return 0;
}

In this example, we create a file called “data.txt” and write the string “Hello, world!” into it using the function fprintf(). The file is closed after writing the data using the function fclose().

Example 2: Reading data from a file

#include <stdio.h>  // Incluye la biblioteca estándar de entrada/salida

int main() {
   FILE *archivo;  // Declara un puntero a FILE para manejar el archivo
   char texto[100];  // Declara un array de caracteres para almacenar el texto leído
   
   // Intenta abrir el archivo "datos.txt" en modo lectura
   archivo = fopen("datos.txt", "r");
   
   // Verifica si el archivo se abrió correctamente
   if (archivo == NULL) {
      printf("No se pudo abrir el archivo.");
      return 1;  // Retorna 1 para indicar que hubo un error
   }
   
   // Lee una línea del archivo (hasta 99 caracteres) y la almacena en 'texto'
   fgets(texto, 100, archivo);
   
   // Imprime el contenido leído del archivo
   printf("El contenido del archivo es: %s", texto);
   
   // Cierra el archivo
   fclose(archivo);
   
   return 0;  // Termina el programa exitosamente
}

In this example, we open the file “data.txt” in read mode using the function fopen() and we read the data using the function fgets(). Then, we display the contents of the file on the screen.

  Difference between algorithm and program: detailed guide

Example 3: Adding data to an existing file

#include <stdio.h>  // Incluye la biblioteca estándar de entrada/salida

int main() {
   FILE *archivo;  // Declara un puntero a FILE para manejar el archivo
   
   // Intenta abrir el archivo "datos.txt" en modo append (agregar)
   // Si el archivo no existe, lo crea. Si existe, se prepara para escribir al final
   archivo = fopen("datos.txt", "a");
   
   // Verifica si el archivo se abrió correctamente
   if (archivo == NULL) {
      printf("No se pudo abrir el archivo.");
      return 1;  // Retorna 1 para indicar que hubo un error
   }
   
   // Escribe la cadena "¡Hola de nuevo!" al final del archivo
   fprintf(archivo, "¡Hola de nuevo!");
   
   // Cierra el archivo
   fclose(archivo);
   
   return 0;  // Termina el programa exitosamente
}

In this example, we open the file “data.txt” in aggregate mode using the “to” mode in the function fopen(). Then we write the string “Hello again!” to the file using fprintf().

Example 4: Reading and writing binary data to a file

#include <stdio.h>  // Incluye la biblioteca estándar de entrada/salida
#include <string.h> // Necesario para strcpy

// Define una estructura llamada Persona
struct Persona {
   char nombre[50];  // Campo para almacenar el nombre (hasta 49 caracteres + '\0')
   int edad;         // Campo para almacenar la edad
};

int main() {
   FILE *archivo;           // Declara un puntero a FILE para manejar el archivo
   struct Persona persona;  // Declara una variable de tipo struct Persona

   // Abre el archivo "datos.bin" en modo escritura binaria
   archivo = fopen("datos.bin", "wb");
   
   // Verifica si el archivo se abrió correctamente
   if (archivo == NULL) {
      printf("No se pudo abrir el archivo.");
      return 1;  // Retorna 1 para indicar que hubo un error
   }
   
   // Inicializa los campos de la estructura persona
   strcpy(persona.nombre, "Juan");
   persona.edad = 25;
   
   // Escribe la estructura persona en el archivo binario
   fwrite(&persona, sizeof(struct Persona), 1, archivo);
   fclose(archivo);  // Cierra el archivo
   
   // Reabre el archivo "datos.bin" en modo lectura binaria
   archivo = fopen("datos.bin", "rb");
   
   // Verifica si el archivo se abrió correctamente
   if (archivo == NULL) {
      printf("No se pudo abrir el archivo.");
      return 1;  // Retorna 1 para indicar que hubo un error
   }
   
   // Lee la estructura Persona desde el archivo binario
   fread(&persona, sizeof(struct Persona), 1, archivo);
   
   // Imprime los datos leídos
   printf("Nombre: %s\nEdad: %d", persona.nombre, persona.edad);
   
   fclose(archivo);  // Cierra el archivo
   
   return 0;  // Termina el programa exitosamente
}

In this example, we create a structure Persona and we write it to a binary file using the function fwrite(). Then, we read the file structure using fread() and we display the data on the screen.

  The Simplex Method: Complete Guide and Applications

Frequently Asked Questions (FAQs)

1. How can I check if a file exists before opening it in C language?

You can use the function fopen() to open the file in read mode. If fopen() bring back NULL, means that the file does not exist. Here is an example:

#include <stdio.h>

int main() {
   FILE *archivo;
   
   archivo = fopen("datos.txt", "r");
   
   if (archivo == NULL) {
      printf("El archivo no existe.");
   } else {
      printf("El archivo existe.");
      fclose(archivo);
   }
   
   return 0;
}

In this example, we open the file “data.txt” in read mode. If fopen() bring back NULL, we display the message “The file does not exist”. Otherwise, we display the message “The file exists” and close the file using fclose().

2. What is the difference between “r” and “rb” opening modes in C language?

The "r" open mode is used to open a file in read mode as text, while the "rb" mode is used to open a file in read mode as binary. The difference lies in how end-of-line characters are handled.

When you open a file in "r" mode, the operating system automatically translates platform-specific end-of-line characters (for example, \n on Unix or \r\n on Windows) to \n. This makes it easier to read and manipulate the data in the file.

On the other hand, when you open a file in “rb” mode, the end-of-line characters are read without translation, meaning they are kept as they are in the file. This is useful when working with binary files that do not contain text.

3. Can I use C language file handling to read and write Unicode text files?

Yes, you can use C language file handling to read and write Unicode text files. However, you should note that C language does not provide native support for Unicode handling. To work with Unicode text files, you must use additional libraries or functions that support the Unicode encoding you want to use, such as UTF-8 or UTF-16.

A commonly used library for handling Unicode in C language is the ICU (International Components for Unicode) library. This library provides functions and tools for working with different Unicode encodings and can be integrated into your program to enable handling of Unicode text files.

  The Powerful Radix Sorting Algorithm

4. What happens if I try to open a file in “w” write mode and the file already exists?

When you try to open a file in “w” write mode and the file already exists, the existing contents of the file will be erased and an empty file will be created. All data previously stored in the file will be lost. Therefore, it is important to be careful when using “w” mode to avoid accidental data loss.

If you want to append data to the end of an existing file without erasing its contents, you must use the append mode "a" instead of the write mode "w". With the "a" mode, data will be appended to the end of the file without affecting its previous contents.

5. What should I do after opening and using a C language file?

After opening and using a file in C language, it is important to close it properly using the function fclose()Closing the file will free up any resources associated with it and ensure that all data is written and stored correctly.

It is good practice to close the file as soon as you have finished reading or writing to it. This prevents potential problems and conflicts if other programs or processes try to access the file while it is still open.

Conclusion

File handling in C is an essential skill for any software developer. It allows you to store and retrieve data persistently, share information between programs, and work with large volumes of data. In this article, we have explored the basics of file handling in C and provided practical examples to help you understand and master this important area of ​​development.

Always remember to close files properly after using them and consider using additional libraries if you need to work with Unicode text files or other specific encodings. With a solid understanding of file handling in C language, you will be well equipped to develop robust and efficient applications that interact with external data effectively.

Now it's your turn! What projects do you have in mind that could benefit from handling files in C language? Share your ideas and start exploring the endless possibilities offered by this powerful tool.