file
1. file.1.man
Manpage of FILE
FILE
Section: User Commands (1)Updated: Con © pero se puede distribuir
Index Return to Main Contents
NOMBRE
file - determina el tipo de ficherosSINOPSIS
file [ -vbczL ] [ -f nombrefichero ] [ -m ficheromágico ] fichero ...DESCRIPCIÓN
Esta página del Manual documenta la versión 3.26 de la orden file . File comprueba cada argumento en un intento de clasificarlo. Hay tres conjuntos de pruebas, efectuadas en este orden: pruebas de sistemas de ficheros, pruebas de números mágicos, y pruebas de lenguajes. La primera prueba que tenga éxito hace que se muestre el tipo del fichero.El tipo mostrado contendrá usualmente una de las palabras text (texto: el fichero contiene solamente caracteres ASCII y probablemente es seguro leerlo en una terminal ASCII ), executable (ejecutable: el fichero contiene el resultado de la compilación de un programa en una forma comprensible para algún núcleo UNIX), o data (datos), que significa cualquier otra cosa (los datos son normalmente `binarios' o no imprimibles). Las excepciones son los formatos de ficheros bien conocidos (volcados de memoria, archivos de tar) que se sabe que contienen datos binarios. Cuando modifique el fichero /usr/share/misc/magic o el propio programa, conserve estas palabras reservadas. Muchos programas dependen de que file muestre todos los ficheros legibles de un directorio con la palabra ``text''. No haga como hicieron en la versión de Berkeley, que cambiaron ``shell commands text'' (texto con órdenes del shell) a ``shell script'' (guión del shell).
Las pruebas de sistemas de ficheros se basan en un examen de la devolución de una llamada al sistema stat(2). El programa comprueba si el fichero está vacío, o si es alguna clase de fichero especial. Cualquier tipo de fichero apropiado al sistema donde se esté (enchufes, enlaces simbólicos, o tuberías con nombre (FIFOs) en aquellos sistemas que las implementen) se intuye si está definido en el fichero de cabecera del sistema sys/stat.h.
Las pruebas de números mágicos se emplean para comprobar ficheros con datos dispuestos en formatos fijos particulares. El ejemplo canónico de esto es un fichero ejecutable binario (programa compilado) a.out, cuyo formato se describe en a.out.h y posiblemente en exec.h en el directorio normal de ficheros de cabecera. Estos ficheros tienen un `número mágico' guardado en una posición particular cerca del principio del fichero, que le dice al sistema operativo UNIX que el fichero es un binario ejecutable, y de qué tipo de entre unos cuantos. El concepto de `número mágico' se ha aplicado por extensión a ficheros de datos. Cualquier fichero con algún identificador invariante en una posición fija y cercana al principio en el fichero puede normalmente describirse de esta forma. La información de estos ficheros se lee del `fichero mágico' /usr/share/misc/magic.
Si un argumento resulta ser un fichero ASCII, file intenta adivinar el lenguaje en el que está escrito. Las pruebas de lenguaje buscan cadenas de caracteres particulares (cf. names.h) que pueden aparecer en cualquier lugar dentro de los primeros bloques de un fichero. Por ejemplo, la palabra clave .br indica que el fichero es con mucha probabilidad un fichero de entrada de troff(1), mientras que la palabra struct puede indicar un programa en C. Estas pruebas son menos confiables que las de los dos grupos anteriores, de forma que se realizan en último lugar. Las rutinas de pruebas de lenguajes también hacen algunas otras comprobaciones (como buscar archivos de tar(1)) y determinan si el mensaje para un fichero desconocido debe ser `ascii text' (texto ASCII) o `data' (datos).
OPCIONES
- -v
- Muestra la versión del programa y acaba.
- -m lista
- Especifica una lista alternativa de ficheros que contienen números mágicos. Ésta puede constar de un solo fichero, o de una lista de ficheros separados por signos de dos puntos.
- -z
- Intenta mirar dentro de ficheros comprimidos.
- -b
- No precede las líneas de salida con los nombres de los ficheros (modo breve).
- -c
- Produce un listado de comprobación de la forma analizada del fichero mágico. Normalmente esto se emplea en conjunción con -m para depurar un nuevo fichero mágico antes de instalarlo.
- -f nombrefichero
- Lee los nombres de los ficheros a examinar desde nombrefichero (uno por línea) antes de la lista de argumentos. O bien nombrefichero o bien por lo menos un argumento que sea un nombre de fichero, debe estar presente; para comprobar la entrada estándar, emplee `-' como un argumento de nombre de fichero.
- -L
- Esta opción hace que se sigan los enlaces simbólicos, como la opción del mismo nombre de ls(1) (en sistemas que admitan enlaces simbólicos).
FICHEROS
/usr/share/misc/magic - lista predeterminada de números mágicosENTORNO
La variable de entorno MAGIC se puede emplear para establecer los ficheros predeterminados con números mágicos.VÉASE TAMBIÉN
magic(4) - descripción del formato del fichero mágico.strings(1), od(1), hexdump(1) - herramientas para examinar ficheros que no son de texto.
CONFORMANCIA CON ESTÁNDARES
Se cree que este programa excede en comportamiento al descrito por SVID en FILE(CMD), tanto como uno pueda deducir del vago lenguaje contenido en dicho documento. Su comportamiento es mayormente compatible con el programa de System V del mismo nombre. Esta versión sabe de más números mágicos, sin embargo, por lo que producirá una salida diferente (si bien más acertada) en muchos casos.
La diferencia más significante entre esta versión y la de System V es
que esta versión trata cualquier espacio en blanco como un
delimitador, de forma que los espacios en cadenas de patrones deben
ser protegidos. Por ejemplo,
>10 string language impress (imPRESS data)
en un fichero mágico existente tendría que cambiarse a
>10 string language\ impress (imPRESS data)
Además, en esta versión, si una cadena patrón contiene una barra
inclinada invertida, debe ser protegida. Por ejemplo
0 string \begindata Andrew Toolkit document
en un fichero mágico existente tendría que cambiarse a
0 string \\begindata Andrew Toolkit document
SunOS en distribuciones 3.2 y siguientes, de Sun Microsystems, incluye
una orden
file(1)
derivada de la de System V, pero con algunas extensiones.
Mi versión difiere de la de Sun sólo en pequeñas cosas.
Incluye la extensión del operador `&', empleado como, por ejemplo,
>16 long&0x7fffffff >0 not stripped
DIRECTORIO MÁGICO
Las entradas del fichero mágico han sido tomadas de varias fuentes, principalmente de USENET, y han contribuido varios autores. Christos Zoulas (su dirección está más abajo) recogerá entradas adicionales o corregidas del fichero mágico. Se distribuirá periódicamente una consolidación de las entradas del fichero mágico.El orden de las entradas en el fichero mágico es significativo. Dependiendo del sistema que esté Ud. usando, el orden en el que estén puestas juntas puede ser incorrecto. Si su vieja orden file emplea un fichero mágico, mantenga el viejo fichero mágico por ahí para comparación (por ejemplo, renómbrelo a /usr/local/share/magic.orig).
HISTORIA
Ha habido una orden file en cada UNIX desde al menos la Versión 6 de Investigación (estando fechada la página del Manual en Enero de 1975). La versión de System V introdujo un cambio importante significativo: la lista externa de tipos con números mágicos. Esto ralentizaba algo el programa pero lo hacía mucho más flexible.Este programa, basado en la versión de System V, ha sido escrito por Ian Darwin sin mirar el código fuente de nadie.
John Gilmore revisó extensamente el código, haciéndolo mejor que la primera versión. Geoff Collyer encontró algunas cosas inadecuadas y proporcionó algunas entradas del fichero mágico. Desde entonces el programa ha ido evolucionando continuamente.
AUTORES
Escrito por Ian F. Darwin, dirección UUCP {utzoo | ihnp4}!darwin!ian, dirección Internet ian@sq.com, dirección postal: P.O. Box 603, Station F, Toronto, Ontario, CANADÁ M4Y 2L8.Alterado por Rob McMahon, cudcv@warwick.ac.uk, en 1989, para extender el operador `&' de un simple `x&y != 0' a `x&y op z'.
Alterado por Guy Harris, guy@netapp.com, en 1993, para:
-
poner el operador `&' ``al viejo estilo'' de nuevo como estaba, porque 1) el cambio de Rob McMahon rompió con el estilo de uso anterior, 2) el operador al ``nuevo estilo'' `&' de SunOS, que esta versión de file también admite, ya maneja también `x&y op z', y 3) el cambio de Rob no estaba documentado en ningún caso;
añadir múltiples niveles de `>';
añadir las palabras clave ``beshort'', ``leshort'', etc., para buscar números en el fichero en un orden de bytes específico, en vez de en el orden de bytes nativo del proceso que esté ejecutando a file.
Cambios por Ian Darwin y varios autores incluyendo a Christos Zoulas (christos@astron.com), 1990-1997.
ADVERTENCIA LEGAL
Derechos de copia © Ian F. Darwin, Toronto, Canadá, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993.Este software no está sujeto y no puede hacerse estarlo a cualquier licencia de la Cía. AT&T, Sun Microsystems Inc., Digital Equipment Co. Inc. (Compaq), Lotus Development Inc., los Regentes de la Universidad de California, el Consorcio X ni MIT, ni la FSF (Fundación del Software Libre).
Este software no está sujeto a ninguna restricción de exportación del Departamento de Comercio de EE.UU., y puede exportarse a cualquier país o planeta.
Se permite a cualquiera usar este software para cualquier propósito en cualquier sistema computador, y alterarlo y redistribuirlo libremente, sujeto a las siguientes restricciones:
1. El autor no es responsable de las consecuencias del uso de este software, sin importar cuán malas fueren, incluso si sobrevienen a causa de defectos en él.
2. El origen de este software no debe ser malinterpretado o alterado, bien sea explícitamente o por omisión. Puesto que son pocos los usuarios que alguna vez leen los fuentes, los créditos deben aparecer en la documentación.
3. Las versiones alteradas deben marcarse explícitamente como tales, y no pueden hacerse aparecer como si fueran el software original. Puesto que son pocos los usuarios que alguna vez leen los fuentes, los créditos deben aparecer en la documentación.
4. Esta nota no puede ser quitada ni alterada (espero que sí pueda ser traducida, N. del T. :-).
Unos pocos ficheros de soporte (getopt, strtok) distribuidos con este paquete son de Henry Spencer y están sujetos a los mismos términos que los de arriba.
Unos pocos ficheros simples de soporte (strtol, strchr) distribuidos con este paquete están en el dominio público; así quedan marcados.
Los ficheros tar.h e is_tar.c fueron escritos por John Gilmore a partir de su programa tar de dominio público, y no están cubiertos por las restricciones de antes.
FALLOS
Debe haber una forma mejor de automatizar la construcción del fichero Magic a partir de todo lo de Magdir. ¿Cuál será? Aún mejor, el fichero mágico debería compilarse a forma binaria (digamos, ndbm(3) o, mejor todavía, cadenas ASCII de longitud fija para su empleo en entornos de red heterogéneos) para un arranque más rápido. Entonces el programa se ejecutaría tan rápido como el de la Versión 7 del mismo nombre, con la flexibilidad de la versión System V.File emplea algunos algoritmos que favorecen la rapidez sobre el acierto, de modo que puede equivocarse al adivinar los contenidos de ficheros ASCII.
El soporte para ficheros ASCII (sobre todo para lenguajes de programación) es simplista, ineficiente, y requiere recompilación para actualizarse.
Debería haber una cláusula ``else'' para seguir una serie de líneas de continuación.
El fichero mágico y las palabras clave deberían admitir expresiones regulares. Su empleo del TAB ASCII como un delimitador de campo es feo y hace difícil editar los ficheros, pero es inamovible.
Podría ser interesante permitir letras mayúsculas en las palabras clave; por ejemplo, órdenes troff(1) frente a macros de páginas man. El soporte de expresiones regulares haría esto más fácil.
Al programa no le gusta FORTRAN. Debería ser capaz de figurarse si el fichero es un programa en FORTRAN viendo algunas palabras reservadas que aparezcan sangradas al principio de la línea. El soporte de expresiones regulares haría esto más fácil.
La lista de palabras clave de ascmagic probablemente deba pertenecer al fichero Magic. Esto podría hacerse usando alguna palabra clave como `*' para el valor de desplazamiento.
Otra mejora sería ordenar el fichero mágico de modo que podamos simplemente ejecutar todas las pruebas para el primer byte, primera palabra, primera palabra larga, etc., una vez que la hayamos cogido. Protestar de conflictos en las entradas del fichero mágico. ¿Construir una regla para que las entradas mágicas se ordenen basadas en el desplazamiento dentro del fichero en vez de en la posición dentro del fichero mágico?
El programa podría proporcionar una forma de dar una estimación de ``cuán buena'' es una estimación. Acabamos quitando adivinaciones (p.ej. ``From '' como los 5 primeros caracteres de un fichero) porque no eran tan buenas como otras tentativas (p. ej. ``Newsgroups:'' frente a "Return-Path:"). Pero aún, si las otras no fueran buenas, debería ser posible utilizar la primera adivinación.
Este programa es más lento que algunas órdenes file comerciales.
Esta página del Manual, y particularmente esta sección, es demasiado larga.
DISPONIBILIDAD
Se puede obtener la última versión original del autor mediante FTP anónimo en ftp.astron.com en el archivo /pub/file/file-X.YY.tar.gz.
Index
- NOMBRE
- SINOPSIS
- DESCRIPCIÓN
- OPCIONES
- FICHEROS
- ENTORNO
- VÉASE TAMBIÉN
- CONFORMANCIA CON ESTÁNDARES
- DIRECTORIO MÁGICO
- HISTORIA
- AUTORES
- ADVERTENCIA LEGAL
- FALLOS
- DISPONIBILIDAD
This document was created by man2html using the manual pages.
Time: 17:11:02 GMT, January 19, 2012
2. file.9.man
Manpage of file
file
Section: Tcl Built-In Commands (n)Updated: 8.3
Index Return to Main Contents
NAME
file - Manipulate file names and attributesSYNOPSIS
file option name ?arg arg ...?DESCRIPTION
This command provides several operations on a file's name or attributes. Name is the name of a file; if it starts with a tilde, then tilde substitution is done before executing the command (see the manual entry for filename for details). Option indicates what to do with the file name. Any unique abbreviation for option is acceptable. The valid options are:
- file atime name ?time?
- Returns a decimal string giving the time at which file name was last accessed. If time is specified, it is 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.
- file attributes name
- file 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
flags and their values. The second form returns the value for the
specific option. The third form sets one or more of the values. The
values are as follows:
-
On Unix, -group gets or sets the group name for the file. A group id can be given to the command, but it returns a group name. -owner gets 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. -permissions sets or retrieves the octal code that chmod(1) uses. This command does also has limited support for setting using the symbolic attributes for chmod(1), of the form [ugo]?[[+-=][rwxst],[...]], where multiple symbolic attributes can be separated by commas (example: u+s,go-rw add sticky bit for user, remove read and write permissions for group and other). A simplified ls style string, of the form rwxrwxrwx (must be 9 characters), is also supported (example: rwxr-xr-t is equivalent to 01755). On versions of Unix supporting file flags, -readonly gives the value or sets or clears the readonly attribute of the file, i.e. the user immutable flag uchg to chflags(1).
On Windows, -archive gives the value or sets or clears the archive attribute of the file. -hidden gives the value or sets or clears the hidden attribute of the file. -longname will expand each path element to its long version. This attribute cannot be set. -readonly gives the value or sets or clears the readonly attribute of the file. -shortname gives a string where every path element is replaced with its short (8.3) version of the name. This attribute cannot be set. -system gives or sets or clears the value of the system attribute of the file.
On Mac OS X and Darwin, -creator gives or sets the Finder creator type of the file. -hidden gives or sets or clears the hidden attribute of the file. -readonly gives or sets or clears the readonly attribute of the file. -rsrclength gives the length of the resource fork of the file, this attribute can only be set to the value 0, which results in the resource fork being stripped off the file.
-
- file channels ?pattern?
- If pattern is not specified, returns a list of names of all registered open channels in this interpreter. If pattern is specified, only those names matching pattern are returned. Matching is determined using the same rules as for string match.
- file copy ?-force? ?--? source target
- file copy ?-force? ?--? source ?source ...? targetDir
- The first form makes a copy of the file or directory source under the pathname target. If target is an existing directory, then the second form is used. The second form makes a copy inside targetDir of each source file listed. If a directory is specified as a source, then the contents of the directory will be recursively copied into targetDir. Existing files will not be overwritten unless the -force option 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 copy will copy soft links (i.e. the links themselves are copied, not the things they point to). 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 -force was 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 a source even if it starts with a -.
- file delete ?-force? ?--? pathname ?pathname ... ?
- Removes the file or directory specified by each pathname argument. Non-empty directories will be removed only if the -force option 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 -force flags is not specified. If the -force option 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 a pathname even if it starts with a -.
- file dirname name
-
Returns a name comprised of all of the path components in name
excluding the last element. If name is a relative file name and
only contains one path element, then returns
``.''.
If name refers to a root directory, then the root directory is
returned. For example,
-
-
file dirname c:/
Note that tilde substitution will only be performed if it is necessary to complete the command. For example,
-
file dirname ~/src/foo.c
-
file dirname ~
-
-
- file executable name
- Returns 1 if file name is executable by the current user, 0 otherwise.
- file exists name
- Returns 1 if file name exists and the current user has search privileges for the directories leading to it, 0 otherwise.
- file extension name
- Returns all of the characters in name after and including the last dot in the last element of name. If there is no dot in the last element of name then returns the empty string.
- file isdirectory name
- Returns 1 if file name is a directory, 0 otherwise.
- file isfile name
- Returns 1 if file name is a regular file, 0 otherwise.
- file join name ?name ...?
-
Takes one or more file names and combines them, using the correct path
separator for the current platform. If a particular name is
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
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 be
linkName, and this command returns the value of the link given by
linkName (i.e. the name of the file it points to). If
linkName is 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.
-
If 2 arguments are given, then these are assumed to be linkName and target. If linkName already exists, or if target does not exist, an error will be returned. Otherwise, Tcl creates a new link called linkName which points to the existing filesystem object at target (which is also the returned value), where the type of the link is platform-specific (on Unix a symbolic link will be the default). This is useful for the case where the user wishes to create a link in a cross-platform way, and does not care what type of link is created.
If the user wishes to make a link of a specific type only, (and signal an error if for some reason that is not possible), then the optional -linktype argument should be given. Accepted values for -linktype are ``-symbolic'' and ``-hard''.
On Unix, symbolic links can be made to relative paths, and those paths must be relative to the actual linkName's location (not to the cwd), but on all other platforms where relative links are not supported, target paths will always be converted to absolute, normalized form before the link is created (and therefore relative paths are interpreted as relative to the cwd). Furthermore, ``~user'' paths are always expanded to absolute form. When creating links on filesystems that either do not support any links, or do not support the specific type requested, an error message will be returned. In particular Windows 95, 98 and ME do not support any links at present, but most Unix platforms support both symbolic and hard links (the latter for files only) and Windows NT/2000/XP (on NTFS drives) support symbolic directory links and hard file links.
-
- file lstat name varName
- Same as stat option (see below) except uses the lstat kernel call instead of stat. This means that if name refers to a symbolic link the information returned in varName is for the link rather than the file it refers to. On systems that do not support symbolic links this option behaves exactly the same as the stat option.
- file mkdir dir ?dir ...?
- Creates each directory specified. For each pathname dir specified, this command will create all non-existing parent directories as well as dir itself. If an existing directory is specified, then no action is taken and no error is returned. Trying to overwrite an existing file with a directory will result in an error. Arguments are processed in the order specified, halting at the first error, if any.
- file mtime name ?time?
- Returns a decimal string giving the time at which file name was last modified. If time is specified, it is a modification time to set for the file (equivalent to Unix touch). 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 modified time cannot be queried or set then an error is generated.
- file nativename name
- Returns the platform-specific name of the file. This is useful if the filename is needed to pass to a platform-specific call, such as to a subprocess via exec under Windows (see EXAMPLES below).
- file normalize name
- Returns a unique normalized path representation for the file-system object (file, directory, link, etc), whose string value can be used as a unique identifier for it. A normalized path is an absolute path which has all ``../'' and ``./'' removed. Also it is one which is in the ``standard'' format for the native platform. On Unix, this 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 concerning the last link in the path is necessary, because Tcl or the user may wish to operate on the actual symbolic link itself (for example file delete, file rename, file copy are defined to operate on symbolic links, not on the things that they point to).
- file owned name
- Returns 1 if file name is owned by the current user, 0 otherwise.
- file pathtype name
- Returns one of absolute, relative, volumerelative. If name refers to a specific file on a specific volume, the path type will be absolute. If name refers to a file relative to the current working directory, then the path type will be relative. If name refers 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 is volumerelative.
- file readable name
- Returns 1 if file name is readable by the current user, 0 otherwise.
- file readlink name
- Returns the value of the symbolic link given by name (i.e. the name of the file it points to). If name is npt a symbolic link or its value cannot be read, then an error is returned. On systems that do not support symbolic links this option is undefined.
- file rename ?-force? ?--? source target
- file 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. 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 will rename symbolic links rather than the things that 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 -- will be treated as a source even if it starts with a -.
- file rootname name
- Returns all of the characters in name up to but not including the last ``.'' character in the last component of name. If the last component of name does not contain a dot, then returns name.
- file separator ?name?
- If no argument is given, returns the character which is 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 accepts name, an error is generated.
- file size name
- Returns a decimal string giving the size of file name in bytes. If the file does not exist or its size cannot be queried then an error is generated.
- file split name
-
Returns a list whose elements are the path components in name. The
first element of the list will have the same path type as name.
All other elements will be relative. Path separators will be discarded
unless they are needed ensure that an element is unambiguously relative.
For example, under Unix
-
-
file split /foo/~bar/baz
-
-
- file stat name varName
- Invokes the stat kernel call on name, and uses the variable given by varName to hold information returned from the kernel call. VarName is treated as an array variable, and the following elements of that variable are set: atime, ctime, dev, gid, ino, mode, mtime, nlink, size, type, uid. Each element except type is a decimal string with the value of the corresponding field from the stat return structure; see the manual entry for stat for details on the meanings of the values. The type element gives the type of the file in the same form returned by the command file type. This command returns an empty string.
- file system name
- Returns a list of one or two elements, the first of which is 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 does not belong to any filesystem, an error is generated.
- file tail name
- Returns all of the characters in the last filesystem component of name. Any trailing directory separator in name is ignored. If name contains no separators then returns name. So, file tail a/b, file tail a/b/ and file tail b all return b.
- 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.
- 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.
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 ~/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
Index
This document was created by man2html using the manual pages.
Time: 17:11:03 GMT, January 19, 2012






