C FILES-File Handling

Dev Frank
7 min readApr 27, 2024

--

Files are the vessels that carry data across the digital expanse, and mastering file handling in C grants you the power to manipulate these vessels with precision and finesse.

Did you know that file handling in C not only allows you to read from and write to files but also empowers you to create, delete, and manipulate them in myriad ways?

Think of files like containers for information, like boxes storing your belongings. Learning how to handle files in C is like becoming a master organizer of these containers. You can not only put things in and take things out of the boxes but also create new ones, get rid of old ones, and rearrange them however you like. It’s like having a superpower to manage your digital stuff efficiently!

In C programming, file handling allows you to work with files stored on your computer’s disk. You can create, open, read from, write to, and close files using functions provided by the standard C library.

HOW TO CREATE A FILE

To create a file in C you declare a pointer of type FILE, and use the fopen() function, which stands for "file open. This function takes two arguments:

  1. Filename (name of the file you want to create)
  2. mode string.
FILE *myfile; // *myfile is a pointer of FILE type
myfile = fopen("filename", "mode_string")

Mode Strings

Mode strings are characters (alphabets) that specifies file access mode in C. The mode string specifies how you want to open the file, whether for reading, writing, or appending, and whether the file should be created if it doesn't already exist.

Types of Mode Strings

“r” — Read-only mode, file must exist.

“w” — Write-only mode, creates/truncates file.

“a” — Append mode, creates file if nonexistent.

“r+” — Read/write mode, file must exist.

“w+” — Read/write mode, creates/truncates file.

“a+” — Read/append mode, creates file if nonexistent.

Example:

#include <stdio.h>
int main(void)
{
FILE *myfileptr;
myfileptr = fopen("example.txt", "w");


fclose(myfileptr);
return 0;
}
  • #include <stdio.h>: Includes the standard input-output library, necessary for file handling functions.
  • int main(void): Defines the main function, the entry point of the program.
  • FILE *myfileptr;: Declares a pointer myfileptr of type FILE, which will be used to represent the file.
  • myfileptr = fopen(“example.txt”, “w”);: Opens a file named “example.txt” in write mode (“w”). If the file doesn’t exist, it will be created. If it does exist, its contents will be truncated (erased). The
  • fopen() function returns a pointer to the opened file, which is then assigned to myfileptr.
  • fclose(myfileptr);: Closes the file represented by myfileptr. This step is essential to ensure that any buffered data is written to the file and that system resources are released properly.
  • return 0;: Indicates that the program execution was successful and terminates the main function.

NOTE: The file “example.txt” will be created on your computer’s disk. By default, it will be created in the same directory where the executable of your C program is located unless you specify a different path when calling fopen().

I am sure you noticed the fclose() function. The fclose() function in C is used to close a file stream that was previously opened using the fopen() function or a similar file opening function.

Closing a file with fclose() is essential to ensure that any buffered data associated with the file is written to the file and that any system resources allocated for the file stream are released, and it also helps in cleaning up unnecessary memory space.

HOW TO WRITE TO A FILE

To start writing into a file, we have to declare a pointer variable with the FILE type. Basically the file needs to be opened, and we do that by using the fopen() function.

I guess you remember what “w” stands for? That’s right!, it’s creates the file specified (if it doesn’t exist) and opens the file for writing.

Then we use functions like fprintf() or fwrite() to write data to the file. fprintf() is typically used for formatted output, while fwrite() is used for binary data.

After you’ve finished writing to the file, close it using the fclose() function to ensure that any buffered data is written to the file and that system resources are released.

Let’s take a simple example:

#include <stdio.h>

int main() {
FILE *myfileptr; // Declare a file pointer

// Open a file named "example.txt" in write mode ("w")
fptr = fopen("example.txt", "w");

// Check if the file was opened successfully
if (myfileptr == NULL) {
printf("Error opening file!\n");
return 1; // Return an error code
}

// Write data to the file using fprintf()
fprintf(myfileptr, "Hello, world!\n");

// Close the file
fclose(myfileptr);

return 0;
}

After running this program, you’ll find a file named “example.txt” in the same directory as your program, containing the text “Hello, world!”.

When we view the file on our computer, it looks like this:

NOTE: When writing to an existing file, previous content is overwritten. This is crucial to be aware of, as it can unintentionally remove existing data.

Append Content To a File

To add contents to a file without overwriting or deleting existing content,, utilize the “a” mode. This mode appends content to the end of the file.

#include <stdio.h>

int main() {
FILE *myfileptr; // Declare a file pointer

// Open a file named "example.txt" in append mode ("a")
myfileptr = fopen("example.txt", "a");

// Check if the file was opened successfully
if (myfileptr == NULL) {
printf("Error opening file!\n");
return 1; // Return an error code
}

// Append data to the file using fprintf()
fprintf(myfileptr, "This is additional content.\n");

// Close the file
fclose(myfileptr);

printf("Data appended to file successfully!\n");

return 0;
}

NOTE: “a” mode works like “w” mode, it creates a new file if the file doesn’t exist and appends content

READ FILES

Reading files in C is a lot more different than writing and appending.

To read from a file, you use the “r” mode.

FILE *myfileptr,

myfileptr = fopen("example.txt", "r"); // Opens the file for reading

Next, we have to make a string that’s large enough to hold all the contents in the file. This is important because when we read data from the file, we need a place to store it in memory before we can do anything with it.

If the string isn’t big enough to hold all the data from the file, we might lose some of the information or encounter errors while reading. So, having a properly sized string ensures that we can safely read and work with all the data from the file.

FILE *myfileptr,

myfileptr = fopen("example.txt", "r"); // Opens the file for reading

char fileString[100]; // Stores the contents of a file

Now let’s look at a function called fgets()

fgets()

fgets() is a C library function used to read a line of text from a file stream or standard input (stdin)

fgets() reads characters from the file stream and stores them into the string pointed to, until either n-1 characters are read, the newline character ‘\n’ is encountered (which is also copied to str), or the end-of-file is reached.

Basically, fgets() is like reading a line from a book. It reads characters from a file or input (like typing on a keyboard) and puts them into a box (a string of letters) until it fills up, finds a new line (pressing "Enter"), or reaches the end of the page (end of the file).

fgets(fileString, 100, myfileptr); 

// fgets takes 3 parameters (str, n, stream)
  1. fileString: This is a pointer to an array where the line read from the file or input stream will be stored. It’s the location where the characters will be placed.
  2. 100: This parameter specifies the maximum number of characters to be copied into the array pointed to by fileString, including the null-terminator character (‘\0’). It helps prevent buffer overflow by limiting the number of characters read.
  3. myfileptr: This is a pointer to a FILE object that identifies the file stream from which fgets() will read the line of text. It could be a file that you’ve opened with fopen() or it could be stdin for reading from standard input (usually the keyboard).

Now let’s put everything in place

#include <stdio.h>

int main(void)
{
FILE *myfileptr;

// Open a file in read mode
myfileptr= fopen("example.txt", "r");

// Store the content of the file
char fileString[100];

// Read the content and store it inside fileString
fgets(fileString, 100, myfileptr);

// Print the file content
printf("%s", fileString);

// Close the file
fclose(myfileptr);

return 0;

}

OUTPUT

Hello World!

NOTE: fgets() function reads only the initial line of the file. If you recall, example.txt contained two lines of text.
To read all lines, you can employ a while loop:

Let’s make some adjustment to the previous example to achieve this:

#include <stdio.h>

int main(void)
{
FILE *myfileptr;

// Open a file in read mode
myfileptr= fopen("example.txt", "r");

// Store the content of the file
char fileString[100];

// Read the content and store it inside fileString and outputs it
while(fgets(fileString, 100, myfileptr)){
printf("%s", fileString);
}

// Close the file
fclose(myfileptr);

return 0;

}

OUTPUT

Hello, World!
This is additional content.

Congratulations, you’ve completed this learning journey and enhanced your skills in C programming. Now, it’s time to put your knowledge into practice. Best of luck!

If you found this content helpful and want to stay updated with more programming insights, here’s how you can support me:
1. Follow me on Medium.
2. Connect with me on X, LinkedIn, and GitHub, where I continue to share valuable programming resources for free.”

--

--

Dev Frank

Passionate tech enthusiast, diving deep into the world of software engineering. Thrilled to share insights with the world. A Software engineering student.