This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Grimtin10's profile picture

Help! fs.exists not working!

Started by Grimtin10, 29 January 2018 - 02:14 AM
Grimtin10 #1
Posted 29 January 2018 - 03:14 AM
So, I'm trying to make a command line based OS, and there is a command called 'run'. I use fs.exists(arg1) (arg1 is the file) to check if the file exists, and if so, run it. So, I assume the problem is that it can't get the current directory it is in, because it can't run files from the root directory of the os. Help please!
LoganDark2 #2
Posted 29 January 2018 - 05:36 AM
Assuming you use the craftOS shell (which has a shell API), shell.dir and fs.combine could help.

Try:

fs.exists(fs.combine(shell.dir(), arg1))

That will combine the current directory with arg1. You might want to skip fs.combine though if arg1 starts with a / - fs.combine doesn't care about the slash.
Exerro #3
Posted 29 January 2018 - 11:31 AM
`fs.exists` doesn't use any of the shell features, it just returns true if the path given exists in the root of the computer. So…

--# a/b exists
--# you've run `cd a`
print(fs.exists("b")) --# false
print(fs.exists("a/b")) --# true

Also note that the normal shell programs like "lua", "shutdown", "clear" etc, don't 'exist' - the shell looks in /rom/programs/ to find them, so `fs.exists("shutdown")` will return false, but `fs.exists("/rom/programs/shutdown")` will return true.

A potential solution to your problem is to do the following (you'll need to change variable names):

if fs.exists(OS_DIR .. "/" .. fileToCheck) then
    runFile(fileToCheck)
end
H4X0RZ #4
Posted 29 January 2018 - 02:40 PM
Another, more robust, solution would be implementing the default functionality of CraftOS. It stores the current directory in a local variable and, unless you give it an absolute path, it will first check if the current dir contains the file, otherwise it will look in all the available "paths" (which, at least on Linux (not sure about CC), is a list of directories separated by colons) before it starts crying out loud because the file doesn't exist.
You could take a look at how `shell.resolve` is implemented.

TL;DR: relative paths are a lie.
Grimtin10 #5
Posted 29 January 2018 - 09:31 PM
Actually, I got it. Anyway thanks for the help! :D/>