Open, read and write to files.
If you’ve been following my blog, you probably are already familiar with this concept of writing data to files. But this time, in addition to traditional writing to text files, we’ll take a look at writing to binary files as well.
Here, let’s take a look at how to open, read, and write files. As you may already know if you’ve been flowing my blog, this is something you’re familiar with for my other series: Linux programming.
Writing to text files
Here’s what we learn in this section:
Access to a file stored in a specified directly -> write specified words to the file.
As shown in image 01, #include<stdlib.h> includes libraries interacting with files.
FILE *file creates a file structure (line 5), and the pointer to access the specified directly’s file is created (line 6).
If it failed for a reason, it exists the program as it’s written in line 9.
fprint() is text-file version of printf().
Also what needs your attention is \r\n in line 12, which is the starting-new-line code for Windows.
*In Linux, it’s \n.
Finally, fclose(file); finishes the file-pointer handling process by closing it.
Since it didn’t work properly on my Windows machine, here’s the executed result on my Linux server as shown in image 02.
Writing to binary files
Line 5’s FILE* file; is the same as shown in image 01’s program.
Line 8’s char wdata[] = { 0x10 , 0x1a , 0x1e , 0x1f }; is the data that is going to be inserted into the target binary file.
Let’s take a look at line 16’s arguments:
wdata is the data that is going to be inserted into the target file as declared in line 8.
sizeof(char): char type data is going to be inserted.
sizeof(wdata): wdata’s size, meaning 4.
file: file-pointer
In line 17, fclose(file); closes the file.
In line 19, file = fopen(“./test.bin”, “rb”); reopens the once-closed file and the following codes will read and print out the file content to the console.
Here is the executed result.