echo '' ;
C Programming Language

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.

NEXT

C – Basic
C – Operator
C – Decision making, Branching, Looping
C – Functions
C – Storage Class
C – Extern
C – Array
C – Pointer
C – Memory Allocation
C – Structure
C – Union
C – Structure and Union
C – Macros
C – Preprocessor and Macros
C – File Management
C – Coding Standard
C – Compilers
C – Compiling Process
C File Management
C Library
C Example

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from ArunEworld

Subscribe now to keep reading and get access to the full archive.

Continue reading