C File Pointer (FILE*)

beginner
20 min

C File Pointer (FILE*)

Welcome to a deep dive into the world of C File Pointers! In this tutorial, we'll explore the FILE* data type, learn how to use it to read and write files, and even delve into some real-world examples. Let's get started! šŸŽÆ

Understanding FILE*

In C programming, the FILE* data type represents a file. It's a pointer to a structure that holds information about the file being accessed. By using FILE*, we can perform various operations on files like reading, writing, and even appending. šŸ’”

c
FILE *fp; // Declaring a file pointer variable

Opening a File

To open a file, we use the fopen() function, which takes two arguments – the file name and the mode of operation. The mode determines whether we want to open the file for reading, writing, or appending.

Here's an example of opening a file for reading:

c
fp = fopen("example.txt", "r");

If the file does not exist, fopen() will return NULL.

Reading from a File

Once a file is opened, we can read its content using functions like fgetc() (read one character) and fgets() (read a line of characters).

c
char ch; while ((ch = fgetc(fp)) != EOF) { // Process the character }
c
char line[100]; fgets(line, sizeof(line), fp); // Process the line

šŸ“ Note: Always check for the end of file (EOF) before assuming a read operation has completed successfully.

Writing to a File

To write to a file, we can use functions like fprintf() (write formatted data) and fputc() (write one character).

c
fprintf(fp, "Hello, World!\n"); fputc('A', fp);

Closing a File

After we're done with a file, we should always close it using the fclose() function to release the resources associated with it.

c
fclose(fp);

Real-World Example: Logging System

Let's create a simple logging system that writes log messages to a file. This will help you understand how file pointers can be used in real-world scenarios. šŸ’”

c
#include <stdio.h> #include <stdlib.h> #include <time.h> void log_message(const char *message) { time_t rawtime; struct tm *timeinfo; FILE *fp; // Open or create the log file fp = fopen("log.txt", "a"); if (fp == NULL) { printf("Couldn't open the log file!\n"); exit(1); } // Get the current time time(&rawtime); timeinfo = localtime(&rawtime); // Write the log message and timestamp fprintf(fp, "[%s %s]: %s\n", asctime(timeinfo), __FUNCTION__, message); // Close the log file fclose(fp); } int main() { log_message("Starting the application."); // Your application code here log_message("Exiting the application."); return 0; }
Quick Quiz
Question 1 of 1

What is the `FILE*` data type in C programming?

With this lesson, you've gained a solid understanding of using file pointers in C programming. Happy coding! šŸŽ‰