Let's start by defining a structure by the name data consisting of a member str, which is a string variable of size 255. Then we will define a file pointer by the name fp, followed by a variable line as a type data structure, so the line becomes a structure with a member called str. We will open a random file, whose name is supplied through a command-line argument, in write-only mode and set the fp file pointer to point at it. If the file cannot be opened in write-only mode for any reason, an error message will be displayed and the program will terminate.
You will be prompted to enter the file contents. The text you enter will be assigned to the str member of the line structure. Because you are supposed to enter stop to indicate that you have finished entering data in the file, the text you entered will be compared with the stop string. If the text entered is not stop, it is written into the file pointed at by the fp file pointer.
Because it is a random file, the text is written into the file through the structure line. The fwrite function writes the number of bytes equal to the size of the structure line into the file pointed at by the fp pointer at its current position. The text in the str member of the line structure is written into the file. When the text entered by the user is stop, the file pointed at by file pointer, the fp file pointer is closed.
Let's use GCC to compile the createrandomfile.c program, as shown in the following statement:
D:\CBook>gcc createrandomfile.c -o createrandomfile
If you get no errors or warnings, this means that the createrandomfile.c program has been compiled into an executable file, createrandomfile.exe. Assuming that we want to create a random file with the name random.data, let's run the executable file, createrandomfile.exe:
D:\CBook>createrandomfile random.data
Enter file content:
This is a random file. I am checking if the code is working
perfectly well. Random file helps in fast accessing of
desired data. Also you can access any content in any order.
stop
Voila! We've successfully created a random file and entered some data in it.
Now let's move on to the next recipe!