You can see in the program that a file pointer is defined by the name fp. We are expecting that a hacker or malicious user might have created a soft link called file1.txt to the existing file, file2.txt. file2.txt is a sensitive file that we don't want to be overwritten or destroyed. To make the program free from any vulnerability, the unlink() function is invoked to remove any links to the file1.txt. This will avoid overwriting of any sensitive file that might be linked with file1.txt.
Also, the open function is invoked to open the file instead of the traditional fopen function. The open function opens the file1.txt file in write-only mode with the O_CREAT and O_EXCL flags, which will fail the open function if the file already exists. This will ensure that no existing sensitive file will be overwritten accidentally in case it is linked to file1.txt. The open function will return a file descriptor for the opened file that will be assigned to the ifp variable.
To work with the file, we need a file stream. So the fdopen function is invoked to associate a file stream with the ifp file descriptor that is generated through the open function. The fdopen function returns a pointer to the file stream that is assigned to the file pointer, fp. In addition, the w mode is used in the fdopen function because although it opens the file in write mode, it will never cause truncation of the file. This makes the program much safer and avoids the accidental deletion of any file.
Thereafter, the program is the same as the previous program. It asks the user to enter certain lines, which are then written in file1.txt. Finally, the file pointed to by the file pointer, fp, is closed.
Let's use GCC to compile the filesolved.c program, as shown in the following screenshot. If you get no errors or warnings, it means the filesolved.c program has compiled into an executable file: filesolved.exe. Let's run this file:
We can verify whether the content entered while running the program has gone into file1.txt or not. To do so, we will open file1.txt to see its contents as follows:
We can see that the content entered by the user has gone into file1.txt.
The contents of file2.txt are intact as follows: