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:
Contents
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
Function | Note | Syntax |
---|---|---|
Fopen() | Open a new file or open an existing file. | FILE *fopen( const char * filename, const char * mode ); |
fclose() | close a file. | int fclose( FILE *fp); |
fputc() | Writing a file. | int fputc( int c, FILE *fp ); |
fgetc() | Reading a file. | int fgetc( FILE * fp ); |
Opening a File: Fopen()
Function
Syntax: fopen(“file_name”,"mode”);
File Modes: generic file handling
- r – Open an existing file for Read purpose
- w – Open 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
, orfread
. - Syntax:
fscanf(filePointer, "%s", buffer);
// Read a string
Writing to a File:
- For writing to a file, you use functions like
fprintf
,fputs
, orfwrite
. - 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
andftell
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.