Since | Origin / Contributor | Maintainer | Source |
---|---|---|---|
2014-12-22 | Zeroday | Zeroday | file.c |
The file module provides access to the file system and its individual files.
The file system is a flat file system, with no notion of subdirectories/folders.
Besides the SPIFFS file system on internal flash, this module can also access FAT partitions on an external SD card if FatFS is enabled.
-- open file in flash:
if file.open("init.lua") then
print(file.read())
file.close()
end
-- or with full pathspec
file.open("/FLASH/init.lua")
-- open file on SD card
if file.open("/SD0/somefile.txt") then
print(file.read())
file.close()
end
Change current directory (and drive). This will be used when no drive/directory is prepended to filenames.
Current directory defaults to the root of internal SPIFFS (/FLASH
) after system start.
!!! note
Function is only available when [FatFS support](../sdcard.md#enabling-fatfs) is compiled into the firmware.
file.chdir(dir)
dir
directory name - /FLASH
, /SD0
, /SD1
, etc.
true
on success, false
otherwise
Determines whether the specified file exists.
file.exists(filename)
filename
file to check
true of the file exists (even if 0 bytes in size), and false if it does not exist
files = file.list()
if files["device.config"] then
print("Config file exists")
end
if file.exists("device.config") then
print("Config file exists")
end
Format the file system. Completely erases any existing file system and writes a new one. Depending on the size of the flash chip in the ESP, this may take several seconds.
!!! note
Function is not supported for SD cards.
file.format()
none
nil
Returns the flash address and physical size of the file system area, in bytes.
!!! note
Function is not supported for SD cards.
file.fscfg()
none
flash address
(number)size
(number)
print(string.format("0x%x", file.fscfg()))
Return size information for the file system. The unit is Byte for SPIFFS and kByte for FatFS.
file.fsinfo()
none
remaining
(number)used
(number)total
(number)
-- get file system info
remaining, used, total=file.fsinfo()
print("\nFile system info:\nTotal : "..total.." (k)Bytes\nUsed : "..used.." (k)Bytes\nRemain: "..remaining.." (k)Bytes\n")
Open and read the contents of a file.
file.getcontents(filename)
filename
file to be opened and read
file contents if the file exists. nil
if the file does not exist.
print(file.getcontents('welcome.txt'))
Lists all files in the file system.
file.list([pattern])
none
a Lua table which contains all {file name: file size} pairs, if no pattern
given. If a pattern is given, only those file names matching the pattern
(interpreted as a traditional Lua pattern,
not, say, a UNIX shell glob) will be included in the resulting table.
file.list
will throw any errors encountered during pattern matching.
l = file.list();
for k,v in pairs(l) do
print("name:"..k..", size:"..v)
end
Mounts a FatFs volume on SD card.
!!! note
Function is only available when [FatFS support](../sdcard.md#enabling-fatfs) is compiled into the firmware and it is not supported for internal flash.
file.mount(ldrv[, pin])
ldrv
name of the logical drive,/SD0
,/SD1
, etc.pin
1~12, IO index for SS/CS, defaults to 8 if omitted.
Volume object
vol = file.mount("/SD0")
vol:umount()
Registers callback functions.
Trigger events are:
rtc
deliver current date & time to the file system. Function is expected to return a table containing the fieldsyear
,mon
,day
,hour
,min
,sec
of current date and time. Not supported for internal flash.
file.on(event[, function()])
event
stringfunction()
callback function. Unregisters the callback iffunction()
is omitted.
nil
sntp.sync(server_ip,
function()
print("sntp time sync ok")
file.on("rtc",
function()
return rtctime.epoch2cal(rtctime.get())
end)
end)
Opens a file for access, potentially creating it (for write modes).
When done with the file, it must be closed using file.close()
.
file.open(filename, mode)
filename
file to be openedmode
:- "r": read mode (the default)
- "w": write mode
- "a": append mode
- "r+": update mode, all previous data is preserved
- "w+": update mode, all previous data is erased
- "a+": append update mode, previous data is preserved, writing is only allowed at the end of file
file object if file opened ok. nil
if file not opened, or not exists (read modes).
-- open 'init.lua', print the first line.
if file.open("init.lua", "r") then
print(file.readline())
file.close()
end
-- open 'init.lua', print the first line.
fd = file.open("init.lua", "r")
if fd then
print(fd:readline())
fd:close(); fd = nil
end
Remove a file from the file system. The file must not be currently open.
###Syntax
file.remove(filename)
filename
file to remove
nil
-- remove "foo.lua" from file system.
file.remove("foo.lua")
Open and write the contents of a file.
file.putcontents(filename, contents)
filename
file to be createdcontents
to be written to the file
true
if the write is ok, nil
on error
file.putcontents('welcome.txt', [[
Hello to new user
-----------------
]])
Renames a file. If a file is currently open, it will be closed first.
file.rename(oldname, newname)
oldname
old file namenewname
new file name
true
on success, false
on error.
-- rename file 'temp.lua' to 'init.lua'.
file.rename("temp.lua","init.lua")
Get attribtues of a file or directory in a table. Elements of the table are:
-
size
file size in bytes -
name
file name -
time
table with time stamp information. Default is 1970-01-01 00:00:00 in case time stamps are not supported (on SPIFFS).year
mon
day
hour
min
sec
-
is_dir
flagtrue
if item is a directory, otherwisefalse
-
is_rdonly
flagtrue
if item is read-only, otherwisefalse
-
is_hidden
flagtrue
if item is hidden, otherwisefalse
-
is_sys
flagtrue
if item is system, otherwisefalse
-
is_arch
flagtrue
if item is archive, otherwisefalse
file.stat(filename)
filename
file name
table containing file attributes
s = file.stat("/SD0/myfile")
print("name: " .. s.name)
print("size: " .. s.size)
t = s.time
print(string.format("%02d:%02d:%02d", t.hour, t.min, t.sec))
print(string.format("%04d-%02d-%02d", t.year, t.mon, t.day))
if s.is_dir then print("is directory") else print("is file") end
if s.is_rdonly then print("is read-only") else print("is writable") end
if s.is_hidden then print("is hidden") else print("is not hidden") end
if s.is_sys then print("is system") else print("is not system") end
if s.is_arch then print("is archive") else print("is not archive") end
s = nil
t = nil
The file
module provides several functions to access the content of a file after it has been opened with file.open()
. They can be used as part of a basic model or an object model:
In the basic model there is max one file opened at a time. The file access functions operate on this file per default. If another file is opened, the previous default file needs to be closed beforehand.
-- open 'init.lua', print the first line.
if file.open("init.lua", "r") then
print(file.readline())
file.close()
end
Files are represented by file objects which are created by file.open()
. File access functions are available as methods of this object, and multiple file objects can coexist.
src = file.open("init.lua", "r")
if src then
dest = file.open("copy.lua", "w")
if dest then
local line
repeat
line = src:read()
if line then
dest:write(line)
end
until line == nil
dest:close(); dest = nil
end
src:close(); dest = nil
end
!!! Attention
It is recommended to use only one single model within the application. Concurrent use of both models can yield unpredictable behavior: Closing the default file from basic model will also close the corresponding file object. Closing a file from object model will also close the default file if they are the same file.
!!! Note
The maximum number of open files on SPIFFS is determined at compile time by `SPIFFS_MAX_OPEN_FILES` in `user_config.h`.
Closes the open file, if any.
file.close()
fd:close()
none
nil
Flushes any pending writes to the file system, ensuring no data is lost on a restart. Closing the open file using file.close()
/ fd:close()
performs an implicit flush as well.
file.flush()
fd:flush()
none
nil
-- open 'init.lua' in 'a+' mode
if file.open("init.lua", "a+") then
-- write 'foo bar' to the end of the file
file.write('foo bar')
file.flush()
-- write 'baz' too
file.write('baz')
file.close()
end
file.close()
/ file.obj:close()
Read content from the open file.
!!! note
The function temporarily allocates 2 * (number of requested bytes) on the heap for buffering and processing the read data. Default chunk size (`FILE_READ_CHUNK`) is 1024 bytes and is regarded to be safe. Pushing this by 4x or more can cause heap overflows depending on the application. Consider this when selecting a value for parameter `n_or_char`.
file.read([n_or_char])
fd:read([n_or_char])
n_or_char
:- if nothing passed in, then read up to
FILE_READ_CHUNK
bytes or the entire file (whichever is smaller). - if passed a number
n
, then read up ton
bytes or the entire file (whichever is smaller). - if passed a string containing the single character
char
, then read untilchar
appears next in the file,FILE_READ_CHUNK
bytes have been read, or EOF is reached.
- if nothing passed in, then read up to
File content as a string, or nil when EOF
-- print the first line of 'init.lua'
if file.open("init.lua", "r") then
print(file.read('\n'))
file.close()
end
-- print the first 5 bytes of 'init.lua'
fd = file.open("init.lua", "r")
if fd then
print(fd:read(5))
fd:close(); fd = nil
end
Read the next line from the open file. Lines are defined as zero or more bytes ending with a EOL ('\n') byte. If the next line is longer than 1024, this function only returns the first 1024 bytes.
file.readline()
fd:readline()
none
File content in string, line by line, including EOL('\n'). Return nil
when EOF.
-- print the first line of 'init.lua'
if file.open("init.lua", "r") then
print(file.readline())
file.close()
end
Sets and gets the file position, measured from the beginning of the file, to the position given by offset plus a base specified by the string whence.
file.seek([whence [, offset]])
fd:seek([whence [, offset]])
whence
- "set": base is position 0 (beginning of the file)
- "cur": base is current position (default value)
- "end": base is end of file
offset
default 0
If no parameters are given, the function simply returns the current file offset.
the resulting file position, or nil
on error
if file.open("init.lua", "r") then
-- skip the first 5 bytes of the file
file.seek("set", 5)
print(file.readline())
file.close()
end
Write a string to the open file.
file.write(string)
fd:write(string)
string
content to be write to file
true
if the write is ok, nil
on error
-- open 'init.lua' in 'a+' mode
if file.open("init.lua", "a+") then
-- write 'foo bar' to the end of the file
file.write('foo bar')
file.close()
end
-- open 'init.lua' in 'a+' mode
fd = file.open("init.lua", "a+")
if fd then
-- write 'foo bar' to the end of the file
fd:write('foo bar')
fd:close()
end
Write a string to the open file and append '\n' at the end.
file.writeline(string)
fd:writeline(string)
string
content to be write to file
true
if write ok, nil
on error
-- open 'init.lua' in 'a+' mode
if file.open("init.lua", "a+") then
-- write 'foo bar' to the end of the file
file.writeline('foo bar')
file.close()
end