To answer this question as literally as possible, the only way to make a file entirely read only is by placing the actual file
in the /rom/ folder of your ComputerCraft installation.
However, it is possible to create a temporary sense of a file being read only.
How?:
If you want to make a file read only, a simple way to do this is to append your startup script with the following code:
local PROTECTED_FILE = "/myFile"
local old_fsOpen = _G["fs"]["open"]
_G["fs"]["open"] = function (path, mode)
mode = string.lower (mode)
if shell.resolveProgram (path) == shell.resolveProgram (PROTECTED_FILE) and (mode == "w" or mode == "wb") then
return nil
end
return old_fsOpen (path, mode)
end
Breakdown:
PROTECTED_FILE: This is the full path on your comptuer to the file that you want to be read only.
old_fsOpen : This is a variable housing the fs.open function which is implemented in the mod itself rather than the bios.
What the hell is _G?!:
_G is the table where all global data is stored during run-time. You can find native functions like 'unpack' and 'next' here. For our purposes, we'll be grabbing the "open" function from the "fs" table in _G.
What's happening?
Once we have a copy of the actual function, we can override the identifier that all other programs will be using to obtain file handles: fs.open.
In this example, we're attaching a function which takes the same arguments as fs.open and simply makes sure that the call isn't trying to get any kind of a handle where any kind of modification to the file is possible.
In the case an attempt at opening the file with writing permissions occurs, then 'nil' will be returned to the calling function so that they cannot invoke any kind of writing function on our file.
Running this script at startup will make it impossible for any program to edit your file!
Have fun and keep your programs safe.
- PaymentOption