C File management

File management in the C programming language involves operations related to reading from and writing to files. Here are some key concepts and functions for file management in C:

File Pointers

  • C uses a file pointer to keep track of the current position in a file.
  • FILE is a structure in C that represents a file stream. You declare a pointer to this structure to work with files.
  • Syntax: FILE *filePointer;

File Functions in C

Table File Functions Summary

Opening a File: Fopen() Function

Syntax: fopen(“file_name”,"mode”);

File Modes: generic file handling

  • r – Open an existing file for Read purpose
  • wOpen an existing file for Write purpose
  • a – Open a file for writing in append mode. If file not exist, then create new file.
  • r+ – Open a file for both Read and Write
  • w+ – Opens a file for Read and Write. If a file is not existing it creates one, else if the file is existing it will be over written.
  • a+

File Modes: Binary file handling

  • rb – Read (Binary file)
  • wb – write (Binary file)
  • ab – append (Binary file)
  • rb+
  • wb+
  • ab+
  • r+b – reading (Binary file)
  • w+b – (Binary file)
  • a+b – (Binary file)

Closing a File: fclose() Function

  • After using a file, it’s important to close it using the fclose function.
  • Syntax: fclose(filePointer);

Reading from a File

  • For reading from a file, you use functions like fscanf, fgets, or fread.
  • Syntax: fscanf(filePointer, "%s", buffer); // Read a string

Writing to a File:

  • For writing to a file, you use functions like fprintf, fputs, or fwrite.
  • Syntax: fprintf(filePointer, "Hello, World!\n");

Error Handling:

  • It’s important to check if file operations are successful. The functions usually return NULL on failure.
  • Syntax: if (filePointer == NULL) { // Handle error }

File Positioning:

  • fseek and ftell functions can be used to set the file position indicator and get the current position.

Syntax:

fseek(filePointer, 0, SEEK_SET); // Move to the beginning of the file long position = ftell(filePointer); // Get the current position

Removing a File:

  • The remove function can be used to delete a file.
  • Syntax: remove("example.txt");

These are basic file management operations in C. Remember to always handle errors and close files after using them to avoid data corruption or loss.

Previous & Next

Please turn AdBlock off, and continue learning

Notice for AdBlock users

Please turn AdBlock off