file(n)
π¦ NAME π¦
file β manipulate file names and attributes π
(you're reading file(n), from Tcl Built-In Commands, and bestie, it ate. no cap.)
β¨ SYNOPSIS β¨
file option name ?arg arg ...?
π DESCRIPTION π
okay so. file is your whole toolkit for messing with a file's name or its attributes β it's giving main character energy for filesystem stuff. ποΈβ¨
In most cases, the name argument is just the name of a file. The option argument is the thing that tells Tcl what you wanna DO with that file name. And listen β any unique abbreviation for option is acceptable, so you can be a little lazy as long as it's not ambiguous. iykyk. π
The valid options are:
file atime name ?time?β returns a decimal string giving the time at which filenamewas last accessed. π°οΈ Iftimeis specified, that's an access time to set for the file. The time is measured in the standard POSIX fashion as seconds from a fixed starting time (often January 1, 1970). If the file does not exist, or its access time cannot be queried or set, then an error is generated. π On Windows, FAT file systems do not support access time. On zipfs file systems, access time is mapped to the modification time.file attributes namefile attributes name ?option?file attributes name ?option value option value...?β this subcommand returns or sets platform-specific values associated with a file. The first form returns a list of the platform-specific options and their values. The second form returns the value for the givenoption. The third form sets one or more of the values. The values are as follows:- On Unix,
-groupgets or sets the group name for the file. A group id can be given to the command, but it returns a group name.-ownergets or sets the user name of the owner of the file. The command returns the owner name, but the numerical id can be passed when setting the owner.-permissionsretrieves or sets a file's access permissions, using octal notation by default. This option also provides limited support for setting permissions using the symbolic notation accepted by thechmodcommand, following the form[ugo]?[[+-=][rwxst],[...]]. Multiple permission specifications may be given, separated by commas. E.g.,u+s,go-rwwould set the setuid bit for a file's owner as well as remove read and write permission for the file's group and other users. Anls-style string of the formrwxrwxrwxis also accepted but must always be 9 characters long. E.g.,rwxr-xr-tis equivalent to01755. On versions of Unix supporting file flags,-readonlyreturns the value of, or sets, or clears the readonly attribute of a file, i.e., the user immutable flag (uchg) to thechflagscommand. - On Windows,
-archivegives the value or sets or clears the archive attribute of the file.-hiddengives the value or sets or clears the hidden attribute of the file.-longnamewill expand each path element to its long version β this attribute cannot be set.-readonlygives the value or sets or clears the readonly attribute of the file.-shortnamegives a string where every path element is replaced with its short (8.3) version of the name if possible. For path elements that cannot be mapped to short names, the long name is retained. This attribute cannot be set.-systemgives or sets or clears the value of the system attribute of the file. - On macOS and Darwin,
-creatorgives or sets the Finder creator type of the file.-hiddengives or sets or clears the hidden attribute of the file.-readonlygives or sets or clears the readonly attribute of the file.-rsrclengthgives the length of the resource fork of the file β this attribute can only be set to the value0, which results in the resource fork being stripped off the file. π - On all platforms, files in zipfs mounted archives return the following attributes. These are all read-only and cannot be directly set. π
-archiveβ the path of the mounted ZIP archive containing the file.-compsizeβ the compressed size of the file within the archive. This is0for directories.-crcβ the CRC of the file if present, else0.-mountβ the path where the containing archive is mounted.-offsetβ the offset of the file within the archive.-uncompsizeβ the uncompressed size of the file. This is0for directories.
- On Unix,
Other attributes may be present in the returned list. These should be ignored, bestie. Don't get distracted. π
file channels ?pattern?β ifpatternis not specified, returns a list of names of all registered open channels in this interpreter. Ifpatternis specified, only those names matchingpatternare returned. Matching is determined using the same rules as forstring match.file copy ?-force? ?--? source targetfile copy ?-force? ?--? source ?source ...? targetDirβ the first form makes a copy of the file or directorysourceunder the pathnametarget. Iftargetis an existing directory, then the second form is used. The second form makes a copy insidetargetDirof eachsourcefile listed. If a directory is specified as asource, then the contents of the directory will be recursively copied intotargetDir. Existing files will not be overwritten unless the-forceoption is specified (when Tcl will also attempt to adjust permissions on the destination file or directory if that is necessary to allow the copy to proceed). When copying within a single filesystem,file copywill copy soft links (i.e. the links themselves are copied, not the things they point to β very "I'm copying the vibe, not the person" of it π«Ά). Trying to overwrite a non-empty directory, overwrite a directory with a file, or overwrite a file with a directory will all result in errors even if-forcewas specified. Arguments are processed in the order specified, halting at the first error, if any. A--marks the end of switches; the argument following the--will be treated as asourceeven if it starts with a-.file delete ?-force? ?--? ?pathname ... ?β removes the file or directory specified by eachpathnameargument. Non-empty directories will be removed only if the-forceoption is specified. When operating on symbolic links, the links themselves will be deleted, not the objects they point to. Trying to delete a non-existent file is not considered an error. π Trying to delete a read-only file will cause the file to be deleted, even if the-forceflag is not specified. If the-forceoption is specified on a directory, Tcl will attempt both to change permissions and move the current directory "pwd" out of the given path if that is necessary to allow the deletion to proceed. Arguments are processed in the order specified, halting at the first error, if any. A--marks the end of switches; the argument following the--will be treated as apathnameeven if it starts with a-.file dirname nameβ returns a name comprised of all of the path components innameexcluding the last element. Ifnameis a relative file name and only contains one path element, then returns ".". Ifnamerefers to a root directory, then the root directory is returned. For example,
file dirname c:/
returns c:/.
file executable nameβ returns1if filenameis executable by the current user,0otherwise. On Windows, which does not have an executable attribute, the command treats all directories and any files with extensionsexe,com,cmdorbatas executable.file exists nameβ returns1if filenameexists and the current user has search privileges for the directories leading to it,0otherwise.file extension nameβ returns all of the characters innameafter and including the last dot in the last element ofname. If there is no dot in the last element ofnamethen returns the empty string.file home ?username?β if no argument is specified, the command returns the home directory of the current user. π This is generally the value of the$HOMEenvironment variable, except that on Windows platforms backslashes in the path are replaced by forward slashes. An error is raised if the$HOMEenvironment variable is not set. π
If username is specified, the command returns the home directory configured in the system for the specified user. Note this may be different than the value of the $HOME environment variable even when username corresponds to the current user. An error is raised if the username does not correspond to a user account on the system.
file isdirectory nameβ returns1if filenameis a directory,0otherwise.file isfile nameβ returns1if filenameis a regular file,0otherwise.file join name ?name ...?β takes one or more file names and combines them, using the correct path separator for the current platform. π§© If a particularnameis relative, then it will be joined to the previous file name argument. Otherwise, any earlier arguments will be discarded, and joining will proceed from the current argument. For example,
file join a b /foo bar
returns /foo/bar.
Note that any of the names can contain separators, and that the result is always canonical for the current platform: / for Unix and Windows.
file link ?-linktype? linkName ?target?β if only one argument is given, that argument is assumed to belinkName, and this command returns the value of the link given bylinkName(i.e. the name of the file it points to). IflinkNameis not a link or its value cannot be read (as, for example, seems to be the case with hard links, which look just like ordinary files), then an error is returned. π΅
Okay so two arguments means they're linkName and target. If linkName already exists, or if target doesn't exist? boom, error, bestie, we don't do that. Otherwise Tcl makes a shiny new link called linkName that points at the existing filesystem object at target (which is also the value you get back β¨), and the type of that link is platform-specific β on Unix a symbolic link is the default. This is the move when you want to create a link in a cross-platform way and genuinely do not care what kind of link shows up. π
But if you want a link of one specific type only β and want it to scream an error if that's somehow not possible β then pass the optional -linktype argument. Accepted values are -symbolic and -hard. those are the only two, no extras. π
On Unix, symbolic links can be made to relative paths, and those paths have to be relative to the actual linkName's location (NOT to the cwd), but on all other platforms where relative links aren't supported, target paths always get converted to absolute, normalized form before the link is created (so relative paths there get read as relative to the cwd). And when you try to create links on filesystems that either don't support any links, or don't support the specific type you requested, you get an error message back. Most Unix platforms support both symbolic and hard links (the hard ones are for files only, sorry). Windows supports symbolic directory links and hard file links on NTFS drives. π
file lstatname ?varName? β same as thestatoption (peep below π) except it uses thelstatkernel call instead ofstat. Which means ifnamerefers to a symbolic link, the info you get back is about the link itself, not the file it points to. On systems that don't support symbolic links this option behaves exactly the same as thestatoption.file mkdir?dir ...? β creates each directory you listed. For every pathname dir you hand over, it creates all the non-existing parent directories plus dir itself. If you point it at a directory that already exists, nothing happens and no error β iconic, unbothered behavior π§. Trying to overwrite an existing file with a directory though? error. Arguments get processed in the order specified, halting at the first error, if any.file mtimename ?time? β returns a decimal string giving the timenamewas last modified. If time is specified, that's the modification time to set for the file (equivalent to Unixtouch). The time is measured the standard POSIX way: seconds from a fixed starting time (oftenJanuary 1, 1970). If the file doesn't exist, or its modified time can't be queried or set, an error is generated. On zipfs file systems, modification time cannot be explicitly set. π«Άfile nativenamename β returns the platform-specific name of the file. Super useful when you need the filename to pass to a platform-specific call, like to a subprocess viaexecunder Windows (check EXAMPLES below).file normalizename β returns a unique normalized path representation for the filesystem object (file, directory, link, etc), and its string value can be used as a unique identifier for it. A normalized path is an absolute path with all"../"and"./"removed. It's also in the"standard"format for the native platform. On Unix that means the segments leading up to the path must be free of symbolic links/aliases (but the very last path component may be a symbolic link), and on Windows it also means we want the long form with that form's case-dependence (which gives us a unique, case-dependent path). The one exception about the last link in the path is necessary because Tcl or the user might wanna operate on the actual symbolic link itself β for examplefile delete,file rename,file copyare defined to operate on symbolic links, not on the things they point to. π¦file ownedname β returns1ifnameis owned by the current user,0otherwise. short, sweet, no notes.file pathtypename β returns one ofabsolute,relative,volumerelative. Ifnamerefers to a specific file on a specific volume, the path type isabsolute. Ifnamerefers to a file relative to the current working directory, the path type isrelative. Ifnamerefers to a file relative to the current working directory on a specified volume, or to a specific file on the current working volume, then the path type isvolumerelative. three flavors, pick your fighter πfile readablename β returns1ifnameis readable by the current user,0otherwise.file readlinkname β returns the value of the symbolic link given byname(i.e. the name of the file it points to). Ifnameis not a symbolic link, or its value can't be read, an error is returned. On systems that don't support symbolic links, this option is undefined. β οΈfile rename?-force? ?--? source targetfile rename?-force? ?--? source ?source ...? targetDir
The first form takes the file or directory specified by pathname source and renames it to target, moving the file if the pathname target specifies a name in a different directory. If target is an existing directory, then the second form is used instead. The second form moves each source file or directory into the directory targetDir. Existing files will not be overwritten unless the -force option is specified. When operating inside a single filesystem, Tcl renames symbolic links rather than the things they point to. Trying to overwrite a non-empty directory, overwrite a directory with a file, or a file with a directory will all result in errors. π Arguments are processed in the order specified, halting at the first error, if any. A -- marks the end of switches; the argument following the -- is treated as a source even if it starts with a -. iykyk.
file rootnamename β returns all of the characters innameup to but not including the last"."character in the last component ofname. If the last component ofnamedoesn't contain a dot, then it just returnsname. πΈfile separator?name? β with no argument, returns the character used to separate path segments for native files on this platform. If a path is given, the filesystem responsible for that path is asked to return its separator character. If no file system acceptsname, an error is generated.file sizename β returns a decimal string giving the size of filenamein bytes. If the file doesn't exist, or its size can't be queried, an error is generated.file splitname β returns a list whose elements are the path components inname. The first element of the list will have the same path type asname. All other elements will be relative. Path separators get discarded unless they're needed to make sure an element is unambiguously relative. βοΈfile statname ?varName? β invokes thestatkernel call onnameand returns a dictionary with the info returned from the kernel call. If varName is given, it uses that variable to hold the information. VarName is treated as an array variable, and in that case the command returns the empty string. The following elements are set:atime,ctime,dev,gid,ino,mode,mtime,nlink,size,type,uid. Each element excepttypeis a decimal string with the value of the corresponding field from thestatreturn structure; see the manual entry forstatfor details on what those values mean. Thetypeelement gives the type of the file in the same form returned by the commandfile type.file systemname β returns a list of one or two elements, the first being the name of the filesystem to use for the file, and the second, if given, an arbitrary string representing the filesystem-specific nature or type of the location within that filesystem. If a filesystem only supports one type of file, the second element may not be supplied. For example the native files have a first element"native", and a second element which when given is a platform-specific type name for the file's system (e.g."NTFS","FAT", on Windows). A generic virtual file system might return the list"vfs ftp"to represent a file on a remote ftp site mounted as a virtual filesystem through an extension called"vfs". If the file doesn't belong to any filesystem, an error is generated. πfile tailname β returns all of the characters in the last filesystem component ofname. Any trailing directory separator innameis ignored. Ifnamecontains no separators, it returnsname. Sofile tail a/b,file tail a/b/andfile tail ball returnb. so satisfying honestly.file tempdir?template? β creates a temporary directory (guaranteed to be newly created and writable by the current script) and returns its name. If template is given, it specifies one of or both of: the existing directory (on a filesystem controlled by the operating system) to contain the temporary directory, and the base part of the directory name. It's considered to have the location of the directory if there is a directory separator in the name, and the base part is everything after the last directory separator (if non-empty). The default containing directory is determined by system-specific operations, and the default base name prefix is"tcl". π
The following output is typical and illustrative; the actual output will vary between platforms:
...and here's what it actually spits out when you run it, bestie βοΈβ¨
% file tempdir
/var/tmp/tcl_u0kuy5
% file tempdir /tmp/myapp
/tmp/myapp_8o7r9L
% file tempdir /tmp/
/tmp/tcl_1mOJHD
% file tempdir myapp
/var/tmp/myapp_0ihS0n
file tempfile ?nameVar? ?template?
Okay so this one makes a temporary file and hands you back a read-write channel opened on it. If nameVar shows up, it names a variable and the name of the temp file gets written into it πΎ β and if nameVar is not there, Tcl will try to arrange for the temp file to get deleted once it's no longer required (so it justβ¦ evaporates, iconic). If template is present, it specifies parts of the template of the filename to use when creating it (like the directory, base-name or extension) β though fair warning, some platforms may ignore some or all of these parts and use a built-in default instead π.
Note that temporary files are only ever created on the native filesystem. As such, they can be relied upon to be used with operating-system native APIs and external programs that require a filename. periodt π
file tildeexpand name
Returns the result of performing tilde substitution on name π . If name begins with a tilde, then the file name will be interpreted as if the first element is replaced with the location of the home directory for the given user. If the tilde is followed immediately by a path separator, the $HOME environment variable is substituted. Otherwise the characters between the tilde and the next separator are taken as a user name, which is used to retrieve the user's home directory for substitution. An error is raised if the $HOME environment variable or user does not exist π.
If the file name does not begin with a tilde, it is returned unmodified. no notes, she stays exactly as she is π«Ά
file type name
Returns a string giving the type of file name, which will be one of file, directory, characterSpecial, blockSpecial, fifo, link, or socket β¨. vibe check passed.
file volumes
Returns the absolute paths to the volumes mounted on the system, as a proper Tcl list π. Without any virtual filesystems mounted as root volumes, on UNIX, the command will always return /, since all filesystems are locally mounted. On Windows, it will return a list of the available local drives (e.g. a:/ c:/). If any virtual filesystem has mounted additional volumes, they will be in the returned list.
file writable name
Returns 1 if file name is writable by the current user, 0 otherwise π₯.
PORTABILITY ISSUES π
Unix
These commands always operate using the real user and group identifiers, not the effective ones. iykyk π
Windows
The file owned subcommand uses the user identifier (SID) of the process token, not the thread token which may be impersonating some other user π.
EXAMPLES π
This procedure shows how to search for C files in a given directory that have a correspondingly-named object file in the current directory:
proc findMatchingCFiles {dir} {
set files {}
switch $::tcl_platform(platform) {
windows {
set ext .obj
}
unix {
set ext .o
}
}
foreach file [glob -nocomplain -directory $dir *.c] {
set objectFile [file tail [file rootname $file]]$ext
if {[file exists $objectFile]} {
lappend files $file
}
}
return $files
}
Rename a file and leave a symbolic link pointing from the old location to the new place π¦:
set oldName foobar.txt
set newName foo/bar.txt
# Make sure that where we're going to move to exists...
if {![file isdirectory [file dirname $newName]]} {
file mkdir [file dirname $newName]
}
file rename $oldName $newName
file link -symbolic $oldName $newName
On Windows, a file can be βstartedβ easily enough (equivalent to double-clicking on it in the Explorer interface) but the name passed to the operating system must be in native format π»:
exec {*}[auto_execok start] {} [file nativename C:/Users/fred/example.txt]
SEE ALSO π
filename(n), open(n), close(n), eof(n), gets(n), tell(n), seek(n), fblocked(n), flush(n)
KEYWORDS π·οΈ
attributes, copy files, delete files, directory, file, move files, name, rename files, stat, user
and that's a wrap bestie, we ate and left no crumbs π
π this whole saga lives in the Tcl docs, version 8.3, filed under file(n) β go be the main character of your own filesystem, mwah ππ
π¦ where this page comes from
- alpine 3.23: tcl9-doc 9.0.3-r0 Β· TCL
- alpine 3.24: tcl9-doc 9.0.3-r2 Β· TCL
- fedora 43: tcl-doc 1:9.0.2-1.fc43 Β· TCL AND GPL-3.0-or-later WITH Bison-exception-2.2 AND BSD-3-Clause
- fedora 44: tcl-doc 1:9.0.2-1.fc44 Β· TCL AND GPL-3.0-or-later WITH Bison-exception-2.2 AND BSD-3-Clause
- nixos 26.05: tcl 9.0.3
- Copyright (c) 1993 The Regents of the University of California
- Copyright (c) 1994-1996 Sun Microsystems, Inc
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms