Разрешенные символы в имени файла windows

Screenshot of a Windows command shell showing filenames in a directory

Filename list, with long filenames containing comma and space characters as they appear in a software display.

A filename or file name is a name used to uniquely identify a computer file in a directory structure. Different file systems impose different restrictions on filename lengths.

A filename may (depending on the file system) include:

  • name – base name of the file
  • extension (format or extension) – indicates the content of the file (e.g. .txt, .exe, .html, .COM, .c~ etc.)

The components required to identify a file by utilities and applications varies across operating systems, as does the syntax and format for a valid filename.

Filenames may contain any arbitrary bytes the user chooses. This may include things like a revision or generation number of the file such as computer code, a numerical sequence number (widely used by digital cameras through the DCF standard), a date and time (widely used by smartphone camera software and for screenshots), and/or a comment such as the name of a subject or a location or any other text to facilitate the searching the files. In fact, even unprintable characters, including bell, 0x00, Return and LineFeed can be part of a filename, although most utilities do not handle them well.

Some people use of the term filename when referring to a complete specification of device, subdirectories and filename such as the Windows C:Program FilesMicrosoft GamesChessChess.exe. The filename in this case is Chess.exe. Some utilities have settings to suppress the extension as with MS Windows Explorer.

History[edit]

On early personal computers using the CP/M operating system, with the File Allocation Table (FAT) filesystem, filenames were always 11 characters. This was referred to as the 8.3 filename with a maximum of an 8 byte name and a maximum of a 3 byte extension. Utilities and applications allowed users to specify filenames without trailing spaces and include a dot before the extension. The dot was not actually stored in the directory. Using only 7 bit characters allowed several file attributes [1]to be included in the actual filename by using the high-order-bit. These attributes included Readonly, Archive, HIDDEN and SYS. Eventually this was too restrictive and the number of characters allowed increased. The attribute bits were moved to a special block of the file including additional information. This led to compatibility problems when moving files between different file systems.[2]

During the 1970s, some mainframe and minicomputers where files on the system were identified by a user name, or account number.

For example, on Digital Equipment Corporation RSTS/E and TOPS-10 operating systems, files were identified by

  • optional device name (one or two characters) followed by an optional unit number, and a colon «:». If not present, it was presumed to be SY:
  • the account number, consisting of a bracket «[«, a pair of numbers separated by a comma, and followed by a close bracket «]». If omitted, it was presumed to be yours.
  • mandatory file name, consisting of 1 to 6 characters (upper-case letters or digits)
  • optional 3-character extension.

On the IBM OS/VS1, OS/390 and MVS operating systems, a file name was up to 44 characters, consisting of upper case letters, digits, and the period. A file name must start with a letter or number, a period must occur at least once each 8 characters, two consecutive periods could not appear in the name, and must end with a letter or digit. By convention, the letters and numbers before the first period was the account number of the owner or the project it belonged to, but there was no requirement to use this convention.

On the McGill University MUSIC/SP system, file names consisted of

  • Optional account number, which was one to four characters followed by a colon.If the account number was missing, it was presumed to be in your account, but if it was not, it was presumed to be in the *COM: pseudo-account, which is where all files marked as public were catalogued.
  • 1-17 character file name, which could be upper case letters or digits, and the period, with the requirement it not begin or end with a period, or have two consecutive periods.

The Univac VS/9 operating system had file names consisting of

  • Account name, consisting of a dollar sign «$», a 1-7 character (letter or digit) username, and a period («.»). If not present it was presumed to be in your account, but if it wasn’t, the operating system would look in the system manager’s account $TSOS. If you typed in a dollar sign only as the account, this would indicate the file was in the $TSOS account unless the first 1-7 character of the file name before the first period matched an actual account name, then that account was used, e.g. ABLE.BAKER is a file in your account, but if not there the system would search for $TSOS.ABLE.BAKER, but if $ABLE.BAKER was specified, the file $TSOS.ABLE.BAKER would be used unless $ABLE was a valid account, then it would look for a file named BAKER in that account.
  • File name, 1-56 characters (letters and digits) separated by periods. File names cannot start or end with a period, nor can two consecutive periods appear.

In 1985, RFC 959 officially defined a pathname to be the character string that must be entered into a file system by a user in order to identify a file.[3]

Around 1995, VFAT, an extension to the MS-DOS FAT filesystem, was introduced in Windows 95 and Windows NT. It allowed mixed-case Unicode long filenames (LFNs), in addition to classic «8.3» names.

References: absolute vs relative[edit]

An absolute reference includes all directory levels. In some systems, a filename reference that does not include the complete directory path defaults to the current working directory. This is a relative reference. One advantage of using a relative reference in program configuration files or scripts is that different instances of the script or program can use different files.

This makes an absolute or relative path composed of a sequence of filenames.

Number of names per file[edit]

Unix-like file systems allow a file to have more than one name; in traditional Unix-style file systems, the names are hard links to the file’s inode or equivalent. Windows supports hard links on NTFS file systems, and provides the command fsutil in Windows XP, and mklink in later versions, for creating them.[4][5] Hard links are different from Windows shortcuts, classic Mac OS/macOS aliases, or symbolic links. The introduction of LFNs with VFAT allowed filename aliases. For example, longfi~1.??? with a maximum of eight plus three characters was a filename alias of «long file name.???» as a way to conform to 8.3 limitations for older programs.

This property was used by the move command algorithm that first creates a second filename and then only removes the first filename.

Other filesystems, by design, provide only one filename per file, which guarantees that alteration of one filename’s file does not alter the other filename’s file.

Length restrictions[edit]

Some filesystems restrict the length of filenames. In some cases, these lengths apply to the entire file name, as in 44 characters on IBM S/370.[6] In other cases, the length limits may apply to particular portions of the filename, such as the name of a file in a directory, or a directory name. For example, 9 (e.g., 8-bit FAT in Standalone Disk BASIC), 11 (e.g. FAT12, FAT16, FAT32 in DOS), 14 (e.g. early Unix), 21 (Human68K), 31, 30 (e.g. Apple DOS 3.2 and 3.3), 15 (e.g. Apple ProDOS), 44 (e.g. IBM S/370),[6] or 255 (e.g. early Berkeley Unix) characters or bytes. Length limits often result from assigning fixed space in a filesystem to storing components of names, so increasing limits often requires an incompatible change, as well as reserving more space.

A particular issue with filesystems that store information in nested directories is that it may be possible to create a file with a complete pathname that exceeds implementation limits, since length checking may apply only to individual parts of the name rather than the entire name. Many Windows applications are limited to a MAX_PATH value of 260, but Windows file names can easily exceed this limit [1]. From Windows 10, version 1607, MAX_PATH limitations have been removed.[7]

Filename extensions[edit]

Many file systems, including FAT, NTFS, and VMS systems, consider as filename extension the part of the file name that consists of one or more characters following the last period in the filename, dividing the filename into two parts: a base name or stem and an extension or suffix used by some applications to indicate the file type. Multiple output files created by an application use the same basename and various extensions. For example, a compiler might use the extension FOR for source input file (for Fortran code), OBJ for the object output and LST for the listing. Although there are some common extensions, they are arbitrary and a different application might use REL and RPT. Extensions have been restricted, at least historically on some systems, to a length of 3 characters, but in general can have any length, e.g., html.

Encoding interoperability[edit]

There is no general encoding standard for filenames.

File names have to be exchanged between software environments for network file transfer, file system storage, backup and file synchronization software, configuration management, data compression and archiving, etc. It is thus very important not to lose file name information between applications. This led to wide adoption of Unicode as a standard for encoding file names, although legacy software might not be Unicode-aware.

Encoding indication interoperability[edit]

Traditionally, filenames allowed any character in their filenames as long as they were file system safe.[2] Although this permitted the use of any encoding, and thus allowed the representation of any local text on any local system, it caused many interoperability issues.

A filename could be stored using different byte strings in distinct systems within a single country, such as if one used Japanese Shift JIS encoding and another Japanese EUC encoding. Conversion was not possible as most systems did not expose a description of the encoding used for a filename as part of the extended file information. This forced costly filename encoding guessing with each file access.[2]

A solution was to adopt Unicode as the encoding for filenames.

In the classic Mac OS, however, encoding of the filename was stored with the filename attributes.[2]

Unicode interoperability[edit]

The Unicode standard solves the encoding determination issue.

Nonetheless, some limited interoperability issues remain, such as normalization (equivalence), or the Unicode version in use. For instance, UDF is limited to Unicode 2.0; macOS’s HFS+ file system applies NFD Unicode normalization and is optionally case-sensitive (case-insensitive by default.) Filename maximum length is not standard and might depend on the code unit size. Although it is a serious issue, in most cases this is a limited one.[2]

On Linux, this means the filename is not enough to open a file: additionally, the exact byte representation of the filename on the storage device is needed. This can be solved at the application level, with some tricky normalization calls.[8]

The issue of Unicode equivalence is known as «normalized-name collision». A solution is the Non-normalizing Unicode Composition Awareness used in the Subversion and Apache technical communities.[9] This solution does not normalize paths in the repository. Paths are only normalized for the purpose of comparisons. Nonetheless, some communities have patented this strategy, forbidding its use by other communities.[clarification needed]

Perspectives[edit]

To limit interoperability issues, some ideas described by Sun are to:

  • use one Unicode encoding (such as UTF-8)
  • do transparent code conversions on filenames
  • store no normalized filenames
  • check for canonical equivalence among filenames, to avoid two canonically equivalent filenames in the same directory.[2]

Those considerations create a limitation not allowing a switch to a future encoding different from UTF-8.

Unicode migration[edit]

One issue was migration to Unicode.
For this purpose, several software companies provided software for migrating filenames to the new Unicode encoding.

  • Microsoft provided migration transparent for the user throughout the VFAT technology
  • Apple provided «File Name Encoding Repair Utility v1.0».[10]
  • The Linux community provided “convmv”.[11]

Mac OS X 10.3 marked Apple’s adoption of Unicode 3.2 character decomposition, superseding the Unicode 2.1 decomposition used previously. This change caused problems for developers writing software for Mac OS X.[12]

Uniqueness[edit]

Within a single directory, filenames must be unique. Since the filename syntax also applies for directories, it is not possible to create a file and directory entries with the same name in a single directory. Multiple files in different directories may have the same name.

Uniqueness approach may differ both on the case sensitivity and on the Unicode normalization form such as NFC, NFD.
This means two separate files might be created with the same text filename and a different byte implementation of the filename, such as L»x00C0.txt» (UTF-16, NFC) (Latin capital A with grave) and L»x0041x0300.txt» (UTF-16, NFD) (Latin capital A, grave combining).[13]

Letter case preservation[edit]

Some filesystems, such as FAT, store filenames as upper-case regardless of the letter case used to create them. For example, a file created with the name «MyName.Txt» or «myname.txt» would be stored with the filename «MYNAME.TXT». Any variation of upper and lower case can be used to refer to the same file. These kinds of file systems are called case-insensitive and are not case-preserving. Some filesystems prohibit the use of lower case letters in filenames altogether.

Some file systems store filenames in the form that they were originally created; these are referred to as case-retentive or case-preserving. Such a file system can be case-sensitive or case-insensitive. If case-sensitive, then «MyName.Txt» and «myname.txt» may refer to two different files in the same directory, and each file must be referenced by the exact capitalization by which it is named. On a case-insensitive, case-preserving file system, on the other hand, only one of «MyName.Txt», «myname.txt» and «Myname.TXT» can be the name of a file in a given directory at a given time, and a file with one of these names can be referenced by any capitalization of the name.

From its original inception, Unix and its derivative systems were case-preserving. However, not all Unix-like file systems are case-sensitive; by default, HFS+ in macOS is case-insensitive, and SMB servers usually provide case-insensitive behavior (even when the underlying file system is case-sensitive, e.g. Samba on most Unix-like systems), and SMB client file systems provide case-insensitive behavior. File system case sensitivity is a considerable challenge for software such as Samba and Wine, which must interoperate efficiently with both systems that treat uppercase and lowercase files as different and with systems that treat them the same.[14]

Reserved characters and words[edit]

File systems have not always provided the same character set for composing a filename. Before Unicode became a de facto standard, file systems mostly used a locale-dependent character set. By contrast, some new systems permit a filename to be composed of almost any character of the Unicode repertoire, and even some non-Unicode byte sequences. Limitations may be imposed by the file system, operating system, application, or requirements for interoperability with other systems.

Many file system utilities prohibit control characters from appearing in filenames. In Unix-like file systems, the null character[15] and the path separator / are prohibited.

In Windows[edit]

File system utilities and naming conventions on various systems prohibit particular characters from appearing in filenames or make them problematic:[16]

Character Name Reason for prohibition
/ slash Used as a path name component separator in Unix-like, Windows, and Amiga systems. (For as long as the SwitChar setting is set to ‘/ ’, the DOS COMMAND.COM shell would consume it as a switch character, but DOS and Windows themselves always accept it as a separator on API level.)
The big solidus (Unicode code point U+29F8) is permitted in Windows filenames.
backslash Used as the default path name component separator in DOS, OS/2 and Windows (even if the SwitChar is set to ‘-‘; allowed in Unix filenames, see Note 1).
The big reverse solidus (U+29F9) is permitted in Windows filenames.
? question mark Used as a wildcard in Unix, Windows and AmigaOS; marks a single character. Allowed in Unix filenames, see Note 1.
The glottal stop ʔ (U+0294), the interrobang (U+203D), the inverted question mark ¿ (U+00BF) and the double question mark (U+2047) are allowed in all filenames.
% percent Used as a wildcard in RT-11; marks a single character. Not special on Windows.
* asterisk
or star
Used as a wildcard in Unix, DOS, RT-11, VMS and Windows. Marks any sequence of characters (Unix, Windows, DOS) or any sequence of characters in either the basename or extension (thus «*.*» in DOS means «all files». Allowed in Unix filenames, see Note 1.
See Star (glyph) for many asterisk-like characters allowed in filenames.
: colon Used to determine the mount point / drive on Windows; used to determine the virtual device or physical device such as a drive on AmigaOS, RT-11 and VMS; used as a pathname separator in classic Mac OS. Doubled after a name on VMS, indicates the DECnet nodename (equivalent to a NetBIOS (Windows networking) hostname preceded by «\».). Colon is also used in Windows to separate an alternative data stream from the main file.
The letter colon (U+A789) and the ratio symbol (U+2236) are permitted in Windows filenames. In the Segoe UI font, used in Windows Explorer, the glyphs for the colon and the letter colon are identical.
| vertical bar
or pipe
Designates software pipelining in Unix, DOS and Windows; allowed in Unix filenames, see Note 1. The mathematical operator (U+2223) is permitted in Windows filenames.
" straight double quote A legacy restriction carried over from DOS. The single quotes (U+0027), (U+2018), and (U+2019) and the curved double quotes (U+201C) and (U+201D) are permitted anywhere in filenames. See Note 1.
< less than Used to redirect input, allowed in Unix filenames, see Note 1. The spacing modifier letter ˂ (U+2C2) is permitted in Windows filenames.
> greater than Used to redirect output, allowed in Unix filenames, see Note 1. The spacing modifier letter ˃ (U+2C3) is permitted in Windows filenames.
. period
or dot
Folder names cannot end with a period in Windows, though the name can end with a period followed by a whitespace character such as a non-breaking space. Elsewhere, the period is allowed, but the last occurrence will be interpreted to be the extension separator in VMS, DOS, and Windows. In other OSes, usually considered as part of the filename, and more than one period (full stop) may be allowed. In Unix, a leading period means the file or folder is normally hidden.
, comma Allowed, but treated as separator by the command line interpreters COMMAND.COM and CMD.EXE on DOS and Windows.
; semicolon Allowed, but treated as separator by the command line interpreters COMMAND.COM and CMD.EXE on DOS and Windows.
= equals sign Allowed, but treated as separator by the command line interpreters COMMAND.COM and CMD.EXE on DOS and Windows.
space Allowed, but the space is also used as a parameter separator in command line applications. This can be solved by quoting the entire filename.

Note 1: While they are allowed in Unix file and folder names, most Unix shells require specific characters such as spaces, <, >, |, , and sometimes :, (, ), &, ;, #, as well as wildcards such as ? and *, to be quoted or escaped:

five and six<seven (example of escaping)
'five and six<seven' or "five and six<seven" (examples of quoting)

The character å (0xE5) was not allowed as the first letter in a filename under 86-DOS and MS-DOS/PC DOS 1.x-2.x, but can be used in later versions.

In Windows utilities, the space and the period are not allowed as the final character of a filename.[17] The period is allowed as the first character, but some Windows applications, such as Windows Explorer, forbid creating or renaming such files (despite this convention being used in Unix-like systems to describe hidden files and directories). Workarounds include appending a dot when renaming the file (that is then automatically removed afterwards), using alternative file managers, creating the file using the command line, or saving a file with the desired filename from within an application.[18]

Some file systems on a given operating system (especially file systems originally implemented on other operating systems), and particular applications on that operating system, may apply further restrictions and interpretations. See comparison of file systems for more details on restrictions.

In Unix-like systems, DOS, and Windows, the filenames «.» and «..» have special meanings (current and parent directory respectively). Windows 95/98/ME also uses names like «…», «….» and so on to denote grandparent or great-grandparent directories.[19] All Windows versions forbid creation of filenames that consist of only dots, although names consist of three dots («…») or more are legal in Unix.

In addition, in Windows and DOS utilities, some words are also reserved and cannot be used as filenames.[18] For example, DOS device files:[20]

CON, PRN, AUX, CLOCK$, NUL
COM0, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9[21]
LPT0, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9[21]
LST (only in 86-DOS and DOS 1.xx)
KEYBD$, SCREEN$ (only in multitasking MS-DOS 4.0)
$IDLE$ (only in Concurrent DOS 386, Multiuser DOS and DR DOS 5.0 and higher)
CONFIG$ (only in MS-DOS 7.0-8.0)

Systems that have these restrictions cause incompatibilities with some other filesystems. For example, Windows will fail to handle, or raise error reports for, these legal UNIX filenames: aux.c,[22] q»uote»s.txt, or NUL.txt.

NTFS filenames that are used internally include:

$Mft, $MftMirr, $LogFile, $Volume, $AttrDef, $Bitmap, $Boot, $BadClus, $Secure,
$Upcase, $Extend, $Quota, $ObjId and $Reparse

Comparison of filename limitations[edit]

System Case
sensitive
Case
preserving
Allowed character set Reserved characters Reserved words Maximum length (characters) Comments
8-bit FAT ? ? 7-bit ASCII (but stored as bytes) first character not allowed to be 0x00 or 0xFF 9 Maximum 9 character base name limit for sequential files (without extension), or maximum 6 and 3 character extension for binary files; see 6.3 filename
FAT12, FAT16, FAT32 No No any SBCS/DBCS OEM codepage 0x00-0x1F 0x7F " * / : < > ? | + , . ; = [ ] (in some environments also: ! @; DOS 1/2 did not allow 0xE5 as first character) Device names including: $IDLE$ AUX COM1…COM4 CON CONFIG$ CLOCK$ KEYBD$ LPT1…LPT4 LST NUL PRN SCREEN$ (depending on AVAILDEV status everywhere or only in virtual DEV directory) 11 Maximum 8 character base name limit and 3 character extension; see 8.3 filename
VFAT No Yes Unicode, using UCS-2 encoding 0x00-0x1F 0x7F " * / : < > ? | 255
exFAT No Yes Unicode, using UTF-16 encoding 0x00-0x1F 0x7F " * / : < > ? | 255
NTFS Optional Yes Unicode, using UTF-16 encoding 0x00-0x1F 0x7F " * / : < > ? | Only in root directory: $AttrDef $BadClus $Bitmap $Boot $LogFile $MFT $MFTMirr pagefile.sys $Secure $UpCase $Volume $Extend $Extend$ObjId $Extend$Quota $Extend$Reparse ($Extend is a directory) 255 Paths can be up to 32,000 characters.

Forbids the use of characters in range 1-31 (0x01-0x1F) and characters » * / : < > ? | unless the name is flagged as being in the Posix namespace. NTFS allows each path component (directory or filename) to be 255 characters long[dubious – discuss].

Windows forbids the use of the MS-DOS device names AUX, CLOCK$, COM0, …, COM9, CON, LPT0, …, LPT9, NUL and PRN, as well as these names with any extension (for example, AUX.txt), except when using Long UNC paths (ex. \.C:nul.txt or \?D:auxcon). (CLOCK$ may be used, if an extension is provided.) The Win32 API strips trailing period (full-stop), and leading and trailing space characters from filenames, except when UNC paths are used. These restrictions only apply to Windows; in Linux distributions that support NTFS, filenames are written using NTFS’s Posix namespace, which allows any Unicode character except / and NUL.

OS/2 HPFS No Yes any 8-bit set |?*<«:>/ 254
Mac OS HFS No Yes any 8-bit set : 255 old versions of Finder are limited to 31 characters
Mac OS HFS+ Optional Yes Unicode, using UTF-16 encoding : on disk, in classic Mac OS, and at the Carbon layer in macOS; / at the Unix layer in macOS 255 Mac OS 8.1 — macOS
macOS APFS Optional Yes Unicode, using UTF-16 encoding[citation needed] In the Finder, filenames containing / can be created, but / is stored as a colon (:) in the filesystem, and is shown as such on the command line. Filenames containing : created from the command line are shown with / instead of : in the Finder, so that it is impossible to create a file that the Finder shows as having a : in its filename. 255 macOS[clarification needed]
most UNIX file systems Yes Yes any 8-bit set / null 255 a leading . indicates that ls and file managers will not show the file by default
z/OS classic MVS filesystem (datasets) No No EBCDIC code pages other than $ # @ — x’C0′ 44 first character must be alphabetic or national ($, #, @)

«Qualified» contains . after every 8 characters or fewer.[23] Partitioned data sets (PDS or PDSE) are divided into members with names of up to 8 characters; the member name is placed in parenthesises after the name of the PDS, e.g. PAYROLL.DEV.CBL(PROG001)

CMS file system No No EBCDIC code pages 8 + 8 Single-level directory structure with disk letters (A–Z). Maximum of 8 character file name with maximum 8 character file type, separated by whitespace. For example, a TEXT file called MEMO on disk A would be accessed as «MEMO TEXT A». (Later versions of VM introduced hierarchical filesystem structures, SFS and BFS, but the original flat directory «minidisk» structure is still widely used.)
early UNIX (AT&T Corporation) Yes Yes any 8-bit set / 14 a leading . indicates a «hidden» file
POSIX «Fully portable filenames»[24] Yes Yes A–Z a–z 0–9 . _ - / null 14 hyphen must not be first character. A command line utility checking for conformance, «pathchk», is part of the IEEE 1003.1 standard and of The Open Group Base Specifications[25]
ISO 9660 No ? A–Z 0–9 _ . «close to 180″(Level 2) or 200(Level 3) Used on CDs; 8 directory levels max (for Level 1, not level 2,3)
Amiga OFS No Yes any 8-bit set : / null 30 Original File System 1985
Amiga FFS No Yes any 8-bit set : / null 30 Fast File System 1988
Amiga PFS No Yes any 8-bit set : / null 107 Professional File System 1993
Amiga SFS No Yes any 8-bit set : / null 107 Smart File System 1998
Amiga FFS2 No Yes any 8-bit set : / null 107 Fast File System 2 2002
BeOS BFS Yes Yes Unicode, using UTF-8 encoding / 255
DEC PDP-11 RT-11 No No RADIX-50 6 + 3 Flat filesystem with no subdirs. A full «file specification» includes device, filename and extension (file type) in the format: dev:filnam.ext.
DEC VAX VMS No From
v7.2
A–Z 0–9 $ - _ 32 per component; earlier 9 per component; latterly, 255 for a filename and 32 for an extension. a full «file specification» includes nodename, diskname, directory/ies, filename, extension and version in the format: OURNODE::MYDISK:[THISDIR.THATDIR]FILENAME.EXTENSION;2 Directories can only go 8 levels deep.
Commodore DOS Yes Yes any 8-bit set :, = $ 16 length depends on the drive, usually 16
HP 250 Yes Yes any 8-bit set SPACE ", : NULL CHR$(255) 6 Disks and tape drives are addressed either using a label (up to 8 characters) or a unit specification. The HP 250 file system does not use directories, nor does it use extensions to indicate file type. Instead the type is an attribute (e.g. DATA, PROG, BKUP or SYST for data files, program files, backups and the OS itself).[26]

See also[edit]

  • File system
  • Fully qualified file name
  • Long filename
  • Path (computing)
  • Slug (Web publishing)
  • Symbolic link
  • Uniform Resource Identifier (URI)
  • Uniform Resource Locator (URL) and Internationalized resource identifier
  • Windows (Win32) File Naming Conventions (Filesystem Agnostic)

References[edit]

  1. ^ «CPM — CP/M disk and file system format».
  2. ^ a b c d e f David Robinson; Ienup Sung; Nicolas Williams (March 2006). «Solaris presentations: File Systems, Unicode, and Normalization» (PDF). San Francisco: Sun.com. Archived from the original (PDF) on July 4, 2012.
  3. ^ RFC 959 IETF.org RFC 959, File Transfer Protocol (FTP)
  4. ^ «Fsutil command description page». Microsoft.com. Retrieved September 15, 2013.
  5. ^ «NTFS Hard Links, Directory Junctions, and Windows Shortcuts». Flex hex. Inv Softworks. Retrieved March 12, 2011.
  6. ^ a b «ddname support with FTP, z/OS V1R11.0 Communications Server IP User’s Guide and Commands z/OS V1R10.0-V1R11.0 SC31-8780-09». IBM.com.
  7. ^ «Maximum Path Length Limitation — Win32 apps».
  8. ^ «Filenames with accents». Ned Batchelder. June 2011. Retrieved September 17, 2013.
  9. ^ «NonNormalizingUnicodeCompositionAwareness — Subversion Wiki». Wiki.apache.org. January 21, 2013. Retrieved September 17, 2013.
  10. ^ «File Name Encoding Repair Utility v1.0». Support.apple.com. June 1, 2006. Retrieved October 2, 2018.
  11. ^ «convmv — converts filenames from one encoding to another». J3e.de. Retrieved September 17, 2013.
  12. ^ «Re: git on MacOSX and files with decomposed utf-8 file names». KernelTrap. May 7, 2010. Archived from the original on March 15, 2011. Retrieved July 5, 2010.
  13. ^ «Cross platform filepath naming conventions — General Programming». GameDev.net. Retrieved September 17, 2013.
  14. ^ «CaseInsensitiveFilenames — The Official Wine Wiki». Wiki.winehq.org. November 8, 2009. Archived from the original on August 18, 2010. Retrieved August 20, 2010.
  15. ^ «The Open Group Base Specifications Issue 6». IEEE Std 1003.1-2001. The Open Group. 2001.
  16. ^ «Naming Files, Paths, and Namespaces (Windows)». Msdn.microsoft.com. August 26, 2013. Retrieved September 17, 2013.
  17. ^ «Windows Naming Conventions». MSDN, Microsoft.com. See last bulleted item.
  18. ^ a b Naming a file msdn.microsoft.com (MSDN), filename restrictions on Windows
  19. ^ Microsoft Windows 95 README for Tips and Tricks, Microsoft, retrieved August 27, 2015
  20. ^ MS-DOS Device Driver Names Cannot be Used as File Names., Microsoft
  21. ^ a b Naming Files, Paths, and Namespaces, Microsoft
  22. ^ Ritter, Gunnar (January 30, 2007). «The tale of «aux.c»«. Heirloom Project.
  23. ^ «Subparameter Definition, z/OS V1R11.0 MVS JCL Reference». IBM.com. Retrieved September 17, 2013.
  24. ^ Lewine, Donald. POSIX Programmer’s Guide: Writing Portable UNIX Programs 1991 O’Reilly & Associates, Inc. Sebastopol, CA pp63-64
  25. ^ pathchk — check pathnames
  26. ^ Hewlett-Packard Company Roseville, CA HP 250 Syntax Reference Rev 1/84 Manual Part no 45260-90063

External links[edit]

  • Data Formats Filename at Curlie
  • File Extension Library
  • FILExt
  • WikiExt — File Extensions Encyclopedia
  • Naming Files, Paths, and Namespaces (MSDN)
  • 2009 POSIX portable filename character set
  • Standard ECMA-208, December 1994, System-Independent Data Format
  • Best Practices for File Naming, USA: Stanford University Libraries, Data Management Services

Screenshot of a Windows command shell showing filenames in a directory

Filename list, with long filenames containing comma and space characters as they appear in a software display.

A filename or file name is a name used to uniquely identify a computer file in a directory structure. Different file systems impose different restrictions on filename lengths.

A filename may (depending on the file system) include:

  • name – base name of the file
  • extension (format or extension) – indicates the content of the file (e.g. .txt, .exe, .html, .COM, .c~ etc.)

The components required to identify a file by utilities and applications varies across operating systems, as does the syntax and format for a valid filename.

Filenames may contain any arbitrary bytes the user chooses. This may include things like a revision or generation number of the file such as computer code, a numerical sequence number (widely used by digital cameras through the DCF standard), a date and time (widely used by smartphone camera software and for screenshots), and/or a comment such as the name of a subject or a location or any other text to facilitate the searching the files. In fact, even unprintable characters, including bell, 0x00, Return and LineFeed can be part of a filename, although most utilities do not handle them well.

Some people use of the term filename when referring to a complete specification of device, subdirectories and filename such as the Windows C:Program FilesMicrosoft GamesChessChess.exe. The filename in this case is Chess.exe. Some utilities have settings to suppress the extension as with MS Windows Explorer.

History[edit]

On early personal computers using the CP/M operating system, with the File Allocation Table (FAT) filesystem, filenames were always 11 characters. This was referred to as the 8.3 filename with a maximum of an 8 byte name and a maximum of a 3 byte extension. Utilities and applications allowed users to specify filenames without trailing spaces and include a dot before the extension. The dot was not actually stored in the directory. Using only 7 bit characters allowed several file attributes [1]to be included in the actual filename by using the high-order-bit. These attributes included Readonly, Archive, HIDDEN and SYS. Eventually this was too restrictive and the number of characters allowed increased. The attribute bits were moved to a special block of the file including additional information. This led to compatibility problems when moving files between different file systems.[2]

During the 1970s, some mainframe and minicomputers where files on the system were identified by a user name, or account number.

For example, on Digital Equipment Corporation RSTS/E and TOPS-10 operating systems, files were identified by

  • optional device name (one or two characters) followed by an optional unit number, and a colon «:». If not present, it was presumed to be SY:
  • the account number, consisting of a bracket «[«, a pair of numbers separated by a comma, and followed by a close bracket «]». If omitted, it was presumed to be yours.
  • mandatory file name, consisting of 1 to 6 characters (upper-case letters or digits)
  • optional 3-character extension.

On the IBM OS/VS1, OS/390 and MVS operating systems, a file name was up to 44 characters, consisting of upper case letters, digits, and the period. A file name must start with a letter or number, a period must occur at least once each 8 characters, two consecutive periods could not appear in the name, and must end with a letter or digit. By convention, the letters and numbers before the first period was the account number of the owner or the project it belonged to, but there was no requirement to use this convention.

On the McGill University MUSIC/SP system, file names consisted of

  • Optional account number, which was one to four characters followed by a colon.If the account number was missing, it was presumed to be in your account, but if it was not, it was presumed to be in the *COM: pseudo-account, which is where all files marked as public were catalogued.
  • 1-17 character file name, which could be upper case letters or digits, and the period, with the requirement it not begin or end with a period, or have two consecutive periods.

The Univac VS/9 operating system had file names consisting of

  • Account name, consisting of a dollar sign «$», a 1-7 character (letter or digit) username, and a period («.»). If not present it was presumed to be in your account, but if it wasn’t, the operating system would look in the system manager’s account $TSOS. If you typed in a dollar sign only as the account, this would indicate the file was in the $TSOS account unless the first 1-7 character of the file name before the first period matched an actual account name, then that account was used, e.g. ABLE.BAKER is a file in your account, but if not there the system would search for $TSOS.ABLE.BAKER, but if $ABLE.BAKER was specified, the file $TSOS.ABLE.BAKER would be used unless $ABLE was a valid account, then it would look for a file named BAKER in that account.
  • File name, 1-56 characters (letters and digits) separated by periods. File names cannot start or end with a period, nor can two consecutive periods appear.

In 1985, RFC 959 officially defined a pathname to be the character string that must be entered into a file system by a user in order to identify a file.[3]

Around 1995, VFAT, an extension to the MS-DOS FAT filesystem, was introduced in Windows 95 and Windows NT. It allowed mixed-case Unicode long filenames (LFNs), in addition to classic «8.3» names.

References: absolute vs relative[edit]

An absolute reference includes all directory levels. In some systems, a filename reference that does not include the complete directory path defaults to the current working directory. This is a relative reference. One advantage of using a relative reference in program configuration files or scripts is that different instances of the script or program can use different files.

This makes an absolute or relative path composed of a sequence of filenames.

Number of names per file[edit]

Unix-like file systems allow a file to have more than one name; in traditional Unix-style file systems, the names are hard links to the file’s inode or equivalent. Windows supports hard links on NTFS file systems, and provides the command fsutil in Windows XP, and mklink in later versions, for creating them.[4][5] Hard links are different from Windows shortcuts, classic Mac OS/macOS aliases, or symbolic links. The introduction of LFNs with VFAT allowed filename aliases. For example, longfi~1.??? with a maximum of eight plus three characters was a filename alias of «long file name.???» as a way to conform to 8.3 limitations for older programs.

This property was used by the move command algorithm that first creates a second filename and then only removes the first filename.

Other filesystems, by design, provide only one filename per file, which guarantees that alteration of one filename’s file does not alter the other filename’s file.

Length restrictions[edit]

Some filesystems restrict the length of filenames. In some cases, these lengths apply to the entire file name, as in 44 characters on IBM S/370.[6] In other cases, the length limits may apply to particular portions of the filename, such as the name of a file in a directory, or a directory name. For example, 9 (e.g., 8-bit FAT in Standalone Disk BASIC), 11 (e.g. FAT12, FAT16, FAT32 in DOS), 14 (e.g. early Unix), 21 (Human68K), 31, 30 (e.g. Apple DOS 3.2 and 3.3), 15 (e.g. Apple ProDOS), 44 (e.g. IBM S/370),[6] or 255 (e.g. early Berkeley Unix) characters or bytes. Length limits often result from assigning fixed space in a filesystem to storing components of names, so increasing limits often requires an incompatible change, as well as reserving more space.

A particular issue with filesystems that store information in nested directories is that it may be possible to create a file with a complete pathname that exceeds implementation limits, since length checking may apply only to individual parts of the name rather than the entire name. Many Windows applications are limited to a MAX_PATH value of 260, but Windows file names can easily exceed this limit [1]. From Windows 10, version 1607, MAX_PATH limitations have been removed.[7]

Filename extensions[edit]

Many file systems, including FAT, NTFS, and VMS systems, consider as filename extension the part of the file name that consists of one or more characters following the last period in the filename, dividing the filename into two parts: a base name or stem and an extension or suffix used by some applications to indicate the file type. Multiple output files created by an application use the same basename and various extensions. For example, a compiler might use the extension FOR for source input file (for Fortran code), OBJ for the object output and LST for the listing. Although there are some common extensions, they are arbitrary and a different application might use REL and RPT. Extensions have been restricted, at least historically on some systems, to a length of 3 characters, but in general can have any length, e.g., html.

Encoding interoperability[edit]

There is no general encoding standard for filenames.

File names have to be exchanged between software environments for network file transfer, file system storage, backup and file synchronization software, configuration management, data compression and archiving, etc. It is thus very important not to lose file name information between applications. This led to wide adoption of Unicode as a standard for encoding file names, although legacy software might not be Unicode-aware.

Encoding indication interoperability[edit]

Traditionally, filenames allowed any character in their filenames as long as they were file system safe.[2] Although this permitted the use of any encoding, and thus allowed the representation of any local text on any local system, it caused many interoperability issues.

A filename could be stored using different byte strings in distinct systems within a single country, such as if one used Japanese Shift JIS encoding and another Japanese EUC encoding. Conversion was not possible as most systems did not expose a description of the encoding used for a filename as part of the extended file information. This forced costly filename encoding guessing with each file access.[2]

A solution was to adopt Unicode as the encoding for filenames.

In the classic Mac OS, however, encoding of the filename was stored with the filename attributes.[2]

Unicode interoperability[edit]

The Unicode standard solves the encoding determination issue.

Nonetheless, some limited interoperability issues remain, such as normalization (equivalence), or the Unicode version in use. For instance, UDF is limited to Unicode 2.0; macOS’s HFS+ file system applies NFD Unicode normalization and is optionally case-sensitive (case-insensitive by default.) Filename maximum length is not standard and might depend on the code unit size. Although it is a serious issue, in most cases this is a limited one.[2]

On Linux, this means the filename is not enough to open a file: additionally, the exact byte representation of the filename on the storage device is needed. This can be solved at the application level, with some tricky normalization calls.[8]

The issue of Unicode equivalence is known as «normalized-name collision». A solution is the Non-normalizing Unicode Composition Awareness used in the Subversion and Apache technical communities.[9] This solution does not normalize paths in the repository. Paths are only normalized for the purpose of comparisons. Nonetheless, some communities have patented this strategy, forbidding its use by other communities.[clarification needed]

Perspectives[edit]

To limit interoperability issues, some ideas described by Sun are to:

  • use one Unicode encoding (such as UTF-8)
  • do transparent code conversions on filenames
  • store no normalized filenames
  • check for canonical equivalence among filenames, to avoid two canonically equivalent filenames in the same directory.[2]

Those considerations create a limitation not allowing a switch to a future encoding different from UTF-8.

Unicode migration[edit]

One issue was migration to Unicode.
For this purpose, several software companies provided software for migrating filenames to the new Unicode encoding.

  • Microsoft provided migration transparent for the user throughout the VFAT technology
  • Apple provided «File Name Encoding Repair Utility v1.0».[10]
  • The Linux community provided “convmv”.[11]

Mac OS X 10.3 marked Apple’s adoption of Unicode 3.2 character decomposition, superseding the Unicode 2.1 decomposition used previously. This change caused problems for developers writing software for Mac OS X.[12]

Uniqueness[edit]

Within a single directory, filenames must be unique. Since the filename syntax also applies for directories, it is not possible to create a file and directory entries with the same name in a single directory. Multiple files in different directories may have the same name.

Uniqueness approach may differ both on the case sensitivity and on the Unicode normalization form such as NFC, NFD.
This means two separate files might be created with the same text filename and a different byte implementation of the filename, such as L»x00C0.txt» (UTF-16, NFC) (Latin capital A with grave) and L»x0041x0300.txt» (UTF-16, NFD) (Latin capital A, grave combining).[13]

Letter case preservation[edit]

Some filesystems, such as FAT, store filenames as upper-case regardless of the letter case used to create them. For example, a file created with the name «MyName.Txt» or «myname.txt» would be stored with the filename «MYNAME.TXT». Any variation of upper and lower case can be used to refer to the same file. These kinds of file systems are called case-insensitive and are not case-preserving. Some filesystems prohibit the use of lower case letters in filenames altogether.

Some file systems store filenames in the form that they were originally created; these are referred to as case-retentive or case-preserving. Such a file system can be case-sensitive or case-insensitive. If case-sensitive, then «MyName.Txt» and «myname.txt» may refer to two different files in the same directory, and each file must be referenced by the exact capitalization by which it is named. On a case-insensitive, case-preserving file system, on the other hand, only one of «MyName.Txt», «myname.txt» and «Myname.TXT» can be the name of a file in a given directory at a given time, and a file with one of these names can be referenced by any capitalization of the name.

From its original inception, Unix and its derivative systems were case-preserving. However, not all Unix-like file systems are case-sensitive; by default, HFS+ in macOS is case-insensitive, and SMB servers usually provide case-insensitive behavior (even when the underlying file system is case-sensitive, e.g. Samba on most Unix-like systems), and SMB client file systems provide case-insensitive behavior. File system case sensitivity is a considerable challenge for software such as Samba and Wine, which must interoperate efficiently with both systems that treat uppercase and lowercase files as different and with systems that treat them the same.[14]

Reserved characters and words[edit]

File systems have not always provided the same character set for composing a filename. Before Unicode became a de facto standard, file systems mostly used a locale-dependent character set. By contrast, some new systems permit a filename to be composed of almost any character of the Unicode repertoire, and even some non-Unicode byte sequences. Limitations may be imposed by the file system, operating system, application, or requirements for interoperability with other systems.

Many file system utilities prohibit control characters from appearing in filenames. In Unix-like file systems, the null character[15] and the path separator / are prohibited.

In Windows[edit]

File system utilities and naming conventions on various systems prohibit particular characters from appearing in filenames or make them problematic:[16]

Character Name Reason for prohibition
/ slash Used as a path name component separator in Unix-like, Windows, and Amiga systems. (For as long as the SwitChar setting is set to ‘/ ’, the DOS COMMAND.COM shell would consume it as a switch character, but DOS and Windows themselves always accept it as a separator on API level.)
The big solidus (Unicode code point U+29F8) is permitted in Windows filenames.
backslash Used as the default path name component separator in DOS, OS/2 and Windows (even if the SwitChar is set to ‘-‘; allowed in Unix filenames, see Note 1).
The big reverse solidus (U+29F9) is permitted in Windows filenames.
? question mark Used as a wildcard in Unix, Windows and AmigaOS; marks a single character. Allowed in Unix filenames, see Note 1.
The glottal stop ʔ (U+0294), the interrobang (U+203D), the inverted question mark ¿ (U+00BF) and the double question mark (U+2047) are allowed in all filenames.
% percent Used as a wildcard in RT-11; marks a single character. Not special on Windows.
* asterisk
or star
Used as a wildcard in Unix, DOS, RT-11, VMS and Windows. Marks any sequence of characters (Unix, Windows, DOS) or any sequence of characters in either the basename or extension (thus «*.*» in DOS means «all files». Allowed in Unix filenames, see Note 1.
See Star (glyph) for many asterisk-like characters allowed in filenames.
: colon Used to determine the mount point / drive on Windows; used to determine the virtual device or physical device such as a drive on AmigaOS, RT-11 and VMS; used as a pathname separator in classic Mac OS. Doubled after a name on VMS, indicates the DECnet nodename (equivalent to a NetBIOS (Windows networking) hostname preceded by «\».). Colon is also used in Windows to separate an alternative data stream from the main file.
The letter colon (U+A789) and the ratio symbol (U+2236) are permitted in Windows filenames. In the Segoe UI font, used in Windows Explorer, the glyphs for the colon and the letter colon are identical.
| vertical bar
or pipe
Designates software pipelining in Unix, DOS and Windows; allowed in Unix filenames, see Note 1. The mathematical operator (U+2223) is permitted in Windows filenames.
" straight double quote A legacy restriction carried over from DOS. The single quotes (U+0027), (U+2018), and (U+2019) and the curved double quotes (U+201C) and (U+201D) are permitted anywhere in filenames. See Note 1.
< less than Used to redirect input, allowed in Unix filenames, see Note 1. The spacing modifier letter ˂ (U+2C2) is permitted in Windows filenames.
> greater than Used to redirect output, allowed in Unix filenames, see Note 1. The spacing modifier letter ˃ (U+2C3) is permitted in Windows filenames.
. period
or dot
Folder names cannot end with a period in Windows, though the name can end with a period followed by a whitespace character such as a non-breaking space. Elsewhere, the period is allowed, but the last occurrence will be interpreted to be the extension separator in VMS, DOS, and Windows. In other OSes, usually considered as part of the filename, and more than one period (full stop) may be allowed. In Unix, a leading period means the file or folder is normally hidden.
, comma Allowed, but treated as separator by the command line interpreters COMMAND.COM and CMD.EXE on DOS and Windows.
; semicolon Allowed, but treated as separator by the command line interpreters COMMAND.COM and CMD.EXE on DOS and Windows.
= equals sign Allowed, but treated as separator by the command line interpreters COMMAND.COM and CMD.EXE on DOS and Windows.
space Allowed, but the space is also used as a parameter separator in command line applications. This can be solved by quoting the entire filename.

Note 1: While they are allowed in Unix file and folder names, most Unix shells require specific characters such as spaces, <, >, |, , and sometimes :, (, ), &, ;, #, as well as wildcards such as ? and *, to be quoted or escaped:

five and six<seven (example of escaping)
'five and six<seven' or "five and six<seven" (examples of quoting)

The character å (0xE5) was not allowed as the first letter in a filename under 86-DOS and MS-DOS/PC DOS 1.x-2.x, but can be used in later versions.

In Windows utilities, the space and the period are not allowed as the final character of a filename.[17] The period is allowed as the first character, but some Windows applications, such as Windows Explorer, forbid creating or renaming such files (despite this convention being used in Unix-like systems to describe hidden files and directories). Workarounds include appending a dot when renaming the file (that is then automatically removed afterwards), using alternative file managers, creating the file using the command line, or saving a file with the desired filename from within an application.[18]

Some file systems on a given operating system (especially file systems originally implemented on other operating systems), and particular applications on that operating system, may apply further restrictions and interpretations. See comparison of file systems for more details on restrictions.

In Unix-like systems, DOS, and Windows, the filenames «.» and «..» have special meanings (current and parent directory respectively). Windows 95/98/ME also uses names like «…», «….» and so on to denote grandparent or great-grandparent directories.[19] All Windows versions forbid creation of filenames that consist of only dots, although names consist of three dots («…») or more are legal in Unix.

In addition, in Windows and DOS utilities, some words are also reserved and cannot be used as filenames.[18] For example, DOS device files:[20]

CON, PRN, AUX, CLOCK$, NUL
COM0, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9[21]
LPT0, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9[21]
LST (only in 86-DOS and DOS 1.xx)
KEYBD$, SCREEN$ (only in multitasking MS-DOS 4.0)
$IDLE$ (only in Concurrent DOS 386, Multiuser DOS and DR DOS 5.0 and higher)
CONFIG$ (only in MS-DOS 7.0-8.0)

Systems that have these restrictions cause incompatibilities with some other filesystems. For example, Windows will fail to handle, or raise error reports for, these legal UNIX filenames: aux.c,[22] q»uote»s.txt, or NUL.txt.

NTFS filenames that are used internally include:

$Mft, $MftMirr, $LogFile, $Volume, $AttrDef, $Bitmap, $Boot, $BadClus, $Secure,
$Upcase, $Extend, $Quota, $ObjId and $Reparse

Comparison of filename limitations[edit]

System Case
sensitive
Case
preserving
Allowed character set Reserved characters Reserved words Maximum length (characters) Comments
8-bit FAT ? ? 7-bit ASCII (but stored as bytes) first character not allowed to be 0x00 or 0xFF 9 Maximum 9 character base name limit for sequential files (without extension), or maximum 6 and 3 character extension for binary files; see 6.3 filename
FAT12, FAT16, FAT32 No No any SBCS/DBCS OEM codepage 0x00-0x1F 0x7F " * / : < > ? | + , . ; = [ ] (in some environments also: ! @; DOS 1/2 did not allow 0xE5 as first character) Device names including: $IDLE$ AUX COM1…COM4 CON CONFIG$ CLOCK$ KEYBD$ LPT1…LPT4 LST NUL PRN SCREEN$ (depending on AVAILDEV status everywhere or only in virtual DEV directory) 11 Maximum 8 character base name limit and 3 character extension; see 8.3 filename
VFAT No Yes Unicode, using UCS-2 encoding 0x00-0x1F 0x7F " * / : < > ? | 255
exFAT No Yes Unicode, using UTF-16 encoding 0x00-0x1F 0x7F " * / : < > ? | 255
NTFS Optional Yes Unicode, using UTF-16 encoding 0x00-0x1F 0x7F " * / : < > ? | Only in root directory: $AttrDef $BadClus $Bitmap $Boot $LogFile $MFT $MFTMirr pagefile.sys $Secure $UpCase $Volume $Extend $Extend$ObjId $Extend$Quota $Extend$Reparse ($Extend is a directory) 255 Paths can be up to 32,000 characters.

Forbids the use of characters in range 1-31 (0x01-0x1F) and characters » * / : < > ? | unless the name is flagged as being in the Posix namespace. NTFS allows each path component (directory or filename) to be 255 characters long[dubious – discuss].

Windows forbids the use of the MS-DOS device names AUX, CLOCK$, COM0, …, COM9, CON, LPT0, …, LPT9, NUL and PRN, as well as these names with any extension (for example, AUX.txt), except when using Long UNC paths (ex. \.C:nul.txt or \?D:auxcon). (CLOCK$ may be used, if an extension is provided.) The Win32 API strips trailing period (full-stop), and leading and trailing space characters from filenames, except when UNC paths are used. These restrictions only apply to Windows; in Linux distributions that support NTFS, filenames are written using NTFS’s Posix namespace, which allows any Unicode character except / and NUL.

OS/2 HPFS No Yes any 8-bit set |?*<«:>/ 254
Mac OS HFS No Yes any 8-bit set : 255 old versions of Finder are limited to 31 characters
Mac OS HFS+ Optional Yes Unicode, using UTF-16 encoding : on disk, in classic Mac OS, and at the Carbon layer in macOS; / at the Unix layer in macOS 255 Mac OS 8.1 — macOS
macOS APFS Optional Yes Unicode, using UTF-16 encoding[citation needed] In the Finder, filenames containing / can be created, but / is stored as a colon (:) in the filesystem, and is shown as such on the command line. Filenames containing : created from the command line are shown with / instead of : in the Finder, so that it is impossible to create a file that the Finder shows as having a : in its filename. 255 macOS[clarification needed]
most UNIX file systems Yes Yes any 8-bit set / null 255 a leading . indicates that ls and file managers will not show the file by default
z/OS classic MVS filesystem (datasets) No No EBCDIC code pages other than $ # @ — x’C0′ 44 first character must be alphabetic or national ($, #, @)

«Qualified» contains . after every 8 characters or fewer.[23] Partitioned data sets (PDS or PDSE) are divided into members with names of up to 8 characters; the member name is placed in parenthesises after the name of the PDS, e.g. PAYROLL.DEV.CBL(PROG001)

CMS file system No No EBCDIC code pages 8 + 8 Single-level directory structure with disk letters (A–Z). Maximum of 8 character file name with maximum 8 character file type, separated by whitespace. For example, a TEXT file called MEMO on disk A would be accessed as «MEMO TEXT A». (Later versions of VM introduced hierarchical filesystem structures, SFS and BFS, but the original flat directory «minidisk» structure is still widely used.)
early UNIX (AT&T Corporation) Yes Yes any 8-bit set / 14 a leading . indicates a «hidden» file
POSIX «Fully portable filenames»[24] Yes Yes A–Z a–z 0–9 . _ - / null 14 hyphen must not be first character. A command line utility checking for conformance, «pathchk», is part of the IEEE 1003.1 standard and of The Open Group Base Specifications[25]
ISO 9660 No ? A–Z 0–9 _ . «close to 180″(Level 2) or 200(Level 3) Used on CDs; 8 directory levels max (for Level 1, not level 2,3)
Amiga OFS No Yes any 8-bit set : / null 30 Original File System 1985
Amiga FFS No Yes any 8-bit set : / null 30 Fast File System 1988
Amiga PFS No Yes any 8-bit set : / null 107 Professional File System 1993
Amiga SFS No Yes any 8-bit set : / null 107 Smart File System 1998
Amiga FFS2 No Yes any 8-bit set : / null 107 Fast File System 2 2002
BeOS BFS Yes Yes Unicode, using UTF-8 encoding / 255
DEC PDP-11 RT-11 No No RADIX-50 6 + 3 Flat filesystem with no subdirs. A full «file specification» includes device, filename and extension (file type) in the format: dev:filnam.ext.
DEC VAX VMS No From
v7.2
A–Z 0–9 $ - _ 32 per component; earlier 9 per component; latterly, 255 for a filename and 32 for an extension. a full «file specification» includes nodename, diskname, directory/ies, filename, extension and version in the format: OURNODE::MYDISK:[THISDIR.THATDIR]FILENAME.EXTENSION;2 Directories can only go 8 levels deep.
Commodore DOS Yes Yes any 8-bit set :, = $ 16 length depends on the drive, usually 16
HP 250 Yes Yes any 8-bit set SPACE ", : NULL CHR$(255) 6 Disks and tape drives are addressed either using a label (up to 8 characters) or a unit specification. The HP 250 file system does not use directories, nor does it use extensions to indicate file type. Instead the type is an attribute (e.g. DATA, PROG, BKUP or SYST for data files, program files, backups and the OS itself).[26]

See also[edit]

  • File system
  • Fully qualified file name
  • Long filename
  • Path (computing)
  • Slug (Web publishing)
  • Symbolic link
  • Uniform Resource Identifier (URI)
  • Uniform Resource Locator (URL) and Internationalized resource identifier
  • Windows (Win32) File Naming Conventions (Filesystem Agnostic)

References[edit]

  1. ^ «CPM — CP/M disk and file system format».
  2. ^ a b c d e f David Robinson; Ienup Sung; Nicolas Williams (March 2006). «Solaris presentations: File Systems, Unicode, and Normalization» (PDF). San Francisco: Sun.com. Archived from the original (PDF) on July 4, 2012.
  3. ^ RFC 959 IETF.org RFC 959, File Transfer Protocol (FTP)
  4. ^ «Fsutil command description page». Microsoft.com. Retrieved September 15, 2013.
  5. ^ «NTFS Hard Links, Directory Junctions, and Windows Shortcuts». Flex hex. Inv Softworks. Retrieved March 12, 2011.
  6. ^ a b «ddname support with FTP, z/OS V1R11.0 Communications Server IP User’s Guide and Commands z/OS V1R10.0-V1R11.0 SC31-8780-09». IBM.com.
  7. ^ «Maximum Path Length Limitation — Win32 apps».
  8. ^ «Filenames with accents». Ned Batchelder. June 2011. Retrieved September 17, 2013.
  9. ^ «NonNormalizingUnicodeCompositionAwareness — Subversion Wiki». Wiki.apache.org. January 21, 2013. Retrieved September 17, 2013.
  10. ^ «File Name Encoding Repair Utility v1.0». Support.apple.com. June 1, 2006. Retrieved October 2, 2018.
  11. ^ «convmv — converts filenames from one encoding to another». J3e.de. Retrieved September 17, 2013.
  12. ^ «Re: git on MacOSX and files with decomposed utf-8 file names». KernelTrap. May 7, 2010. Archived from the original on March 15, 2011. Retrieved July 5, 2010.
  13. ^ «Cross platform filepath naming conventions — General Programming». GameDev.net. Retrieved September 17, 2013.
  14. ^ «CaseInsensitiveFilenames — The Official Wine Wiki». Wiki.winehq.org. November 8, 2009. Archived from the original on August 18, 2010. Retrieved August 20, 2010.
  15. ^ «The Open Group Base Specifications Issue 6». IEEE Std 1003.1-2001. The Open Group. 2001.
  16. ^ «Naming Files, Paths, and Namespaces (Windows)». Msdn.microsoft.com. August 26, 2013. Retrieved September 17, 2013.
  17. ^ «Windows Naming Conventions». MSDN, Microsoft.com. See last bulleted item.
  18. ^ a b Naming a file msdn.microsoft.com (MSDN), filename restrictions on Windows
  19. ^ Microsoft Windows 95 README for Tips and Tricks, Microsoft, retrieved August 27, 2015
  20. ^ MS-DOS Device Driver Names Cannot be Used as File Names., Microsoft
  21. ^ a b Naming Files, Paths, and Namespaces, Microsoft
  22. ^ Ritter, Gunnar (January 30, 2007). «The tale of «aux.c»«. Heirloom Project.
  23. ^ «Subparameter Definition, z/OS V1R11.0 MVS JCL Reference». IBM.com. Retrieved September 17, 2013.
  24. ^ Lewine, Donald. POSIX Programmer’s Guide: Writing Portable UNIX Programs 1991 O’Reilly & Associates, Inc. Sebastopol, CA pp63-64
  25. ^ pathchk — check pathnames
  26. ^ Hewlett-Packard Company Roseville, CA HP 250 Syntax Reference Rev 1/84 Manual Part no 45260-90063

External links[edit]

  • Data Formats Filename at Curlie
  • File Extension Library
  • FILExt
  • WikiExt — File Extensions Encyclopedia
  • Naming Files, Paths, and Namespaces (MSDN)
  • 2009 POSIX portable filename character set
  • Standard ECMA-208, December 1994, System-Independent Data Format
  • Best Practices for File Naming, USA: Stanford University Libraries, Data Management Services

Если вам кажется, что нет ничего проще, чем придумать имя для файла или папки, то скорее всего вы ошибаетесь. Существуют правила из-за которых нельзя назвать файл любым именем как обычный физический предмет. Для начала проясним, что такое имя файла, и как оно используется.

Понятия «путь» и «имя файла»

Очень часто в компьютерной литературе используются термины «путь» и «имя файла» под разными значениями. Обычно под словом «путь» понимают адрес или расположение файла, т. е. диск, папка и подпапки в которых расположен файл. Однако Microsoft и другие считают, что в путь к файлу входит не только его расположение но и само имя файла. А некоторые подразумевают под словом «путь» только имена файла и папок, в которых он расположен, без указания диска. Некоторые пользователи полагают, что «имя файла» не включает расширение. В данной статье расширение всегда является частью имени файла. На примере ниже синим цветом выделен путь к файлу, а красным имя файла.
X:папкаподпапка
файл.расширение

Зарезервированные символы и имена

Большинство часто употребляемых символов разрешается использовать в имени файла. Имя файла не должно содержать „<” (знак меньше),  „>” (знак больше), „:” (двоеточие), „«” (двойные кавычки), „/” (слеш), „” (обратный слеш), „|” (вертикальная черта), „?” (вопросительный знак), „*” (звездочка), а также не может заканчиваться точкой или пробелом. Файлы также нельзя называть зарезервированными именами устройств: CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, и LPT9.

Ограничения на длины имен файлов и путей

Существуют ограничения на длину имени файла и на длину пути. Абсолютное ограничение длины имени файла вместе включая путь к нему равно 260 символам. Этот предел называют термином MAX_PATH. На самом же деле на практике пределы для имен еще меньше из-за ряда других ограничений. Например, каждая строка на конце должна содержать так называемый нулевой символ, который обозначает конец строки. Несмотря на то, что маркер конца строки не отображается, он учитывается как отдельный символ при подсчете длины, а значит остается 259 символов доступных для имени файла и пути к нему. Первые три символа в пути используются для обозначения диска (например, C:). Это уменьшает предел для имен папок, подпапок и файла до 256 символов.

На имя объекта (папки или файла) наложено ограничение длины 255 символов. Этот предел действителен только, если объект не расположен внутри папки. Так как при расположении объекта внутри папки, сумма длин всех папок в которых он расположен, разделителей и имени объекта ограничена 256 символами, то предел длины самого имени объекта меньше 255 символов.

Имена папок и файлов

Обычная ситуация — Вы создаете папку или файл и называете как Вам хотелось бы. Вроде бы ничего особенного, но порой появляются сообщения о неверном или неправильном имени папки или файла и о содержании недопустимых символов в ней. Обычное такое бывает когда Вы вставляете скопированный текст в поле имени папки, а он содержит всякие символы. Вот сейчас и рассмотрим какие символы и какие ограничения выставляет Windows на имя папки и файла.

На заметку: быстро переименовать папку/файл можно выделив и нажав кнопку F2.

Первое ограничение — это на количество знаков в имени папки или файла. Имя не должно превышать 255 символов . В принципе это нормальное решение, ведь столько символов вполне могут вместить нормальное имя. Вы же не будете в него целый стих записывать, к примеру.

Второе ограничение — это использование запрещенных символов .
Знаки меньше/больше , двоеточие : , двойные кавычки ” , слеш / и обратный слеш , вертикальная черта | , знак вопроса ? , звездочка * , кроме этого имя не может заканчиваться точкой или пробелом .
Если Вы использовали в назначении имени один из этих 9ти знаков, то система выдаст сообщение:

Имена папок и файлов

Почему нельзя? Да потому что это служебные знаки системы и зарезервированы для выполнения специальных функций:
меньше/больше — перенаправление вывода,
: — отделяет букву диска или имя альтернативного потока данных,
» — используется для указания путей, содержащих пробелы,
— разделитель подкаталогов,
/ — разделитель ключей командного интерпретатора,
| — обозначение конвейера,
? — заменяющий символ (маска «один любой символ»).

Кроме всего этого ограничение есть ещё и на определенные имена такие как: CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9 .
Это тоже служебные имена и система их использует для своих целей.

Немного уточню насчёт символа точки. В имени папок можно использовать сколько угодно точек, но если Вы создаете имя файла, то у него должно быть расширение. И расширением будет считаться то, что будет идти после последней точки.

Как в Windows 10 включить поддержку пути к файлам длиной более 260 символов

Благодаря Anniversary Update для Windows 10 вы можете, наконец, отказаться от ограничения максимального пути в 260 символов в Windows. Вам просто нужно внести небольшие изменения в реестр Windows или групповую политику. Далее рассказано, как это сделать.

До Windows 95, операционная система Windows допускала только имена файлов длиной восемь символов с расширением файла из трёх символов, обычно называемое именем файла 8.3. Windows 95 отказалась от этого, чтобы разрешить длинные имена файлов, но по-прежнему ограничивала максимальную длину пути (которая включает полный путь к папке и имя файла) не более 260 символами. Этот предел был установлен тогда и действует до сих пор. Если вы когда-либо сталкивались с этим ограничением, скорее всего, это было, когда вы пытались скопировать папки с глубоким вложением в другие папки, например, при копировании содержимого жёсткого диска в папку на другом диске. В Windows 10 Anniversary Update наконец добавлена возможность отказаться от этой максимальной длины пути.

Есть одна оговорка. Этот новый параметр не обязательно будет работать с каждым приложением, но он будет работать с большинством. В частности, любые современные приложения должны быть в порядке, как и все 64-битные приложения. Более старые 32-битные приложения должны быть подготовлены специальным образом, что на самом деле означает, что разработчик указал в файле манифеста приложения, что приложение поддерживает более длинные пути. У большинства популярных 32-битных приложений проблем не должно быть. Тем не менее вы ничем не рискуете если выполните эту настройку. Если приложение не работает, единственное, что произойдёт, это то, что оно не сможет открывать или сохранять файлы, сохранённые в местах, где полный путь превышает 260 символов.

Windows Home: как снять ограничение в 260 символов на путь имени файла

Если у вас версия Windows Home, вам придётся отредактировать реестр Windows, чтобы внести эти изменения. Вы также можете сделать это таким образом, если у вас Windows Pro или Enterprise, но вы чувствуете себя более комфортно, работая в реестре, чем редактор групповой политики. (Однако, если у вас есть Pro или Enterprise, мы рекомендуем использовать более простой редактор групповой политики, как описано в следующем разделе.)

Стандартное предупреждение: редактор реестра является мощным инструментом, и неправильное его использование может сделать вашу систему нестабильной или даже неработоспособной. Это довольно простая настройка, и пока вы придерживаетесь инструкции, у вас не должно быть никаких проблем. Тем не менее если вы никогда не работали с реестром ОС раньше, изучите более подробно о том, как использовать редактор реестра, прежде чем приступить к работе. И обязательно сделайте резервную копию реестра (и вашего компьютера!) перед внесением изменений.

Чтобы начать, откройте редактор реестра, нажав «Пуск» и напечатав «regedit». Нажмите Enter, чтобы открыть редактор реестра и дать ему разрешение вносить изменения в свой компьютер.

В редакторе реестра используйте левую боковую панель, чтобы перейти к следующему ключу:

Справа найдите значение с именем LongPathsEnabled и дважды щёлкните его. Если вы не видите значения в списке, вам нужно создать его, щёлкнув правой кнопкой мыши по ключу FileSystem, выбрав New > DWORD (32-bit) Value, а затем присвоив имя новому значению LongPathsEnabled.

В окне свойств значения измените значение с 0 на 1 в поле «Значение» и нажмите кнопку «ОК».

Теперь вы можете закрыть редактор реестра и перезагрузить компьютер (или выйти из своей учётной записи и войти снова). Если вы хотите отменить изменения, просто вернитесь к значению LongPathsEnabled и установите его значение от 1 до 0.

Включите поддержку длинных имён файлов одним кликом

Если вы не хотите погружаться в Реестр самостоятельно, мы создали два файла с настройками реестра, которые вы можете использовать. Один хак удаляет ограничение пути в 260 символов, а другой хак восстанавливает ограничение по умолчанию. Оба сжаты в следующий файл ZIP. Дважды щёлкните тот, который вы хотите использовать, кликните по подсказкам и перезагрузите компьютер.

Эти хаки на самом деле являются просто ключом FileSystem, урезанным до значения LongPathsEnabled, которое мы описали выше, а затем экспортированным в файл .REG. Запуск хака «Remove 260 Character Path Limit.reg» устанавливает значение LongPathsEnabled равным 1. Запуск хака «Restore 260 Character Path Limit (Default).reg» устанавливает значение обратно в 0.

Windows Pro или Enterprise: как снять ограничение в 260 символов на путь имени файла с помощью редактора локальной групповой политики

Если вы используете Windows 10 Pro или Enterprise, самый простой способ отменить ограничение на длину пути файла в 260 символов это использовать редактор локальной групповой политики. Это довольно мощный инструмент, поэтому, если вы никогда не использовали его раньше, стоит потратить некоторое время на изучение того, что он может делать. Кроме того, если вы находитесь в сети компании, сделайте всем одолжение и сначала проконсультируйтесь с вашим администратором. Если ваш рабочий компьютер является частью домена, вполне вероятно, что он является частью групповой политики домена, которая в любом случае заменит локальную групповую политику.

В Windows 10 Pro или Enterprise нажмите «Пуск», введите gpedit.msc и нажмите Enter.

В редакторе локальной групповой политики в левой панели перейдите к Конфигурация компьютера > Административные шаблоны > Система > Файловая система. Справа найдите элемент «Включить длинные пути Win32» и дважды щёлкните его.

В открывшемся окне свойств выберите параметр «Включено» и нажмите «ОК».

Теперь вы можете выйти из редактора локальной групповой политики и перезагрузить компьютер (или выйти и снова войти), чтобы изменения вступили в силу. Если в любой момент вы хотите отменить изменения, просто следуйте той же процедуре и установите для этого параметра значение «Отключено» или «Не настроено».

Максимальный предел пути не является чем-то важным, что обязательно нужно изменить, но для некоторых людей это, безусловно, это ограничение было довольно досадным. Windows 10 наконец-то добавила возможность убрать это ограничение. Вам достаточно просто внести небольшие и быстрые изменения в реестр или групповую политику, чтобы это произошло.

Имя файла не должно содержать следующих знаков как разрешить

Если вы загружаете на сайт файлы (документы, изображения, архивы и пр.), и подразумевается, что доступ к этим файлам будет публичный, а не ограниченный списком избранных товарищей, нужно иметь в виду, что различные многочисленные пользователи сети интернет используют разные устройства ( настольные компьютеры, ноутбуки, планшеты, смартфоны, . ) и разные операционные системы (Mac, PC, Linux, . ).

Символы, запрещенные в имени файла

И чтобы у всех ваши файлы адекватно открывались, отображались и скачивались, нужно перестраховаться и избегать использования в названиях файлов и каталогах сайта запрещенных символов.

Использование правильных названий для папок и файлов очень важно для web, особенно — для загружаемых файлов, таких как PDF-файлы, документы MS Word, электронные таблицы MS Excel и др.

Создавая и формируя любой документ, мы не имеем ограничений по используемым символам внутри него и можем писать в нем любые, даже запрещенные символы. Но для сохранения файла нужно присваивать ему имя с учетом некоторых правил и ограничений интернета.

Не используйте следующие запрещенные символы в названиях директорий и файлов:

# — pound (решетка) < — left angle bracket (знак «меньше») $ — dollar sign (доллар) + — plus sign (плюс)
% — percent (процент) > — right angle bracket (знак «больше») ! — exclamation point (восклицательный знак) ` — backtick (обратная кавычка)
& — ampersand (амперсенд) * — asterisk (звездочка) — single quotes (одинарные кавычки) | — pipe (вертикальная черта)
— left bracket (левая фигурная скобка) ? — question mark (вопросительный знак) — double quotes (двойные кавычки) = — equal sign (равно)
> — right bracket (правая фигурная скобка) / — forward slash (прямой слеш) : — colon (двоеточие)
— back slash (обратный слеш) — blank spaces (пробел) @ — at sign (собачка)

Не каждый сайт или сервер имеет механизм проверки файлов и, зачастую, даже если имя файла содержит запрещенные символы, вы все равно сможете загрузить его на сервер. Но вот скачать его, скорее всего, никто не сможет, особенно, через web-интерфейс.

Рассмотрим ситуацию, в которой пользователь загрузил на сайт PDF-файл, содержащий в названии символ «Решетка» (pound) — #. Сервер имеет операционную систему Linux. Поведение сервера при наличии таких символов в именах файлов будет неадекватным.

В этом случае апач считает что URL — это все, что находится перед знаком «Решетка», а все что после него — это якорь на HTML-странице, т.е. ссылка на конкретное место в HTML-документе. Соответственно, он не распознает его, как файл и не отдает пользователю.

Так как на большинстве сайтов используется автоматический Загрузчик файлов, который без лишних вопросов загружает то, что пользователь выбирает на своем компьютере. Поведение апача верное, но он не может отличить файл от html, для него всё является ссылкой, поэтому он так и будет обрабатывать.

Таким образом, нужно всего лишь не использовать символы запрещенные для имен и папок на сайте. Это самое простое в реализации.

Имена файлов в разных системах

Полное
имя файла
(полный путь к файлу) в
Windows-системах состоит из буквы диска,
после которого ставится двоеточие и
обратная наклонная черта (обратный
слеш), затем через обратные слеши
перечисляются подкаталоги, в конце
пишется имя файла. Пример:

C:WindowsSystem32calc.exe

в UNIX-системах
полный путь состоит из слеша (/),
обозначающего корневой каталог, после
которого через слеши перечисляются
подкаталоги, в конце пишется имя файла.
Пример:

/usr/local/bin/gcc

Имя файла
состоит из двух частей, разделенных
точкой:

  • Название (до точки, часто также называют
    именем);

  • Расширение
    (необязательная часть).

Полное имя
файла (включая расширение) в Windows может
содержать до 260 символов, данное значение
определено константой MAX_PATH в Windows API;
например максимально допустимое полное
имя файла на диске C будет таким «C:<256
символов>NULL». Однако юникодные версии
некоторых функций позволяют использовать
имена файлов, содержащие до 32000 символов,
такие имена начинаются с префикса
«\?». Пример:

\?C:WindowsSystem32calc.exe

При
использовании префикса «\?» необходимо
указывать абсолютный путь к файлу,
относительные пути не допускаются. При
использовании относительных путей
максимальное полное имя файла ограничено
константой MAX_PATH (260 символов).

В Windows в
имени файла запрещено использование
некоторых служебных символов: «», «/»,
«:», «*», «?», «»», «<», «>», «|». В Linux
эти символы, кроме «/», допустимы, хотя
использовать их следует с осторожностью,
так как некоторые из них могут иметь
специальный смысл, а также из соображений
совместимости с другими ОС.

Название
файлу (до точки) рекомендуется давать
осмысленное, говорящее о назначении
файла, дабы избежать путаницы в дальнейшем.

. Расширение
имени

Расширение
имени файла
(англ. filename extension,
часто говорят просто расширение файла
или расширение) — последовательность
символов, добавляемых к имени файла и
предназначенных для идентификации типа
(формата) файла. Это один из распространённых
способов, с помощью которых пользователь
или программное обеспечение компьютера
может определить тип данных, хранящихся
в файле.

Расширение
обычно отделяется от основной части
имени файла точкой. В операционных
системах CP/M и MS-DOS длина расширения была
ограничена тремя символами, в современных
операционных системах это ограничение
отсутствует. Иногда могут использоваться
несколько расширений, следующих друг
за другом, например, «.tar.gz».

В файловой
системе FAT16 имя файла и расширение
являлись отдельными сущностями, а точка,
разделявшая их, реально не являлась
частью полного имени файла и служила
лишь для визуального отделения имени
файла от расширения. В файловых системах
FAT32 и NTFS точка стала обычным разрешённым
символом в имени файла, поэтому ограничения
на количество точек в имени файла в этих
системах и их местоположения были сняты
(за некоторыми исключениями, например,
все конечные точки в именах файлов
просто отбрасываются). Поэтому стандартный
шаблон поиска *.* не имеет больше
практического смысла, достаточно задать
*, так как символ точки теперь
подпадает под понятие любого символа.

Некоторые
операционные системы или менеджеры
файлов могут устанавливать соответствия
между расширениями файлов и приложениями.
Когда пользователь открывает файл с
зарегистрированным расширением,
автоматически запускается соответствующая
этому расширению программа. Некоторые
расширения показывают, что файл сам
является программой.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]

  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #

Компьютер работает с информацией, которая может быть текстовой, графической, в аудио или видео формате. Вся информация, обрабатываемая на компьютере, хранится в файлах. Например, файл — это фото, картинка, ролик, документ, презентация, программа и так далее.

типы файлов

Понятие файла является одним из базовых понятий компьютерной грамотности.

Файл – это поименованная область памяти на компьютерном носителе.

Другими словами, файлом называется набор данных на компьютерном носителе (жёсткий диск, флешка, карта памяти в смартфоне, CD и DVD диск и т.п.), у которого есть свое имя (имя файла).

Имя файла

Какие можно использовать символы в имени файла? В именах файлов рекомендуется использовать русские и латинские буквы, цифры, пробелы и знаки препинания.

Однако имя файла не следует начинать с точки, а также использовать в имени квадратные [ ] или фигурные { } скобки. Недопустимыми для имен файлов являются следующие служебные символы  / | : * ? “ < >

Существует ли максимальная длина имени файла? Длина имени файла не должна превышать 255 символов. На самом деле, обычно хватает 20-25 символов.

Операционная система Windows  не делает различий между строчными и прописными буквами для имен файлов. Это означает, что не получится хранить в одной и той же папке файлы, имена которых различаются только регистром. Например, два имени файла «Название.doc» и «НАЗВАНИЕ.doc» для Windows будет одним именем для одного и того же файла.

Что такое тип файла или формат файла

Как Вы считаете, могут ли быть в одной папке несколько файлов с одинаковым именем PRIMER? Это возможно при условии, что у имени  PRIMER будут разные расширения.

Расширение имени файла указывает на его тип (иногда еще говорят — формат файла). Таким образом,

  • «тип файла»,
  • «формат файла»,
  • «расширение файла»,
  • «расширение имени файла»

— все эти понятия, по сути, одно и то же.

Например,

PRIMER.doc(x) – типом файла является документ Word (или файл в формате Ворда),

PRIMER.bmp – типом файла является рисунок,

PRIMER.avi – типом файла является видеофайл,

PRIMER.wav – типом файла является аудиофайл.

Все эти файлы имеют разные имена (за счет разных расширений имени файла) и могут храниться в одном и том же месте, т.е. в одной папке.

Если проводить аналогию с именами людей, то имя файла совпадает с именем человека, а расширение имени файла – с фамилией человека. Соответственно, PRIMER.doc и PRIMER.bmp по этой аналогии то же самое, что Иван Петров и Иван Сидоров.

Файлы с именами PRIMER.doc и VARIANT.docx – это два брата из одного семейства документов (с одинаковым расширением .docx). Аналогично, например, Иван Петров и Федор Петров – братья из одной семьи Петровых.

Тип файла (то есть, расширение имени файла) – это часть имени файла, которая начинается с точки, после которой стоят несколько символов.

Распространены типы (расширения), состоящие из трех букв – .doc,  .txt, .bmp, .gif и.т.д. Регистр не имеет значения, поэтому .doc и .DOC – это одно и то же расширение документа, один тип файла.

Расширение является необязательным атрибутом в имени файла, то есть его может и не быть. В таком случае в конце имени файла точка, как правило, не ставится.

Зачем нужен тип файла

Расширение в имени файла хоть и не обязательно, но все-таки желательно, так как оно указывает операционной системе Windows на тип файла. Проще говоря, тип файла является подсказкой для Windows, с помощью какой программы системе Windows следует этот файл открывать.

Например, расширение .docx указывает, что файл следует открывать с помощью редактора Word, а расширение .cdr –  на то, что файл открывается графической программой Corel Draw.

Есть зарезервированные (служебные) имена, которые нельзя использовать в качестве имен файлов, так как они являются именами устройств:

PRN – принтер,

COM1-COM4 – устройства, присоединяемые к последовательным портам 1-4,

AUX – то же, что COM1,

LPT1-LPT4 – устройства, присоединяемые к параллельным портам 1-4 (как правило, принтеры),

CON (consol) – при вводе – клавиатура, при выводе – экран,

NUL – «пустое» устройство.

Запрещенные символы в именах файлов

Приведу примеры имен файлов, которые являются недопустимыми:

5<>8/7.txt – символы «<», «>» и  «/» запрещены,

В чем вопрос? – символ «?» запрещен,

PRN.bmp – здесь PRN зарезервированное имя.

Что такое значок файла или иконка файла

В зависимости от типа файла на экран Windows выводятся различные значки (иконки). Первый пример касается значка текстового редактора:

— значок документа, обрабатываемого редактором Word, и имеющего расширение .doc.

Второй пример относится к архивному файлу. Это тот файл, который был обработан с помощью программы-архиватора WinRAR (сокращенно RAR):

— значок сжатых (архивных) файлов, обрабатываемых архиватором RAR, и имеющих расширение .rar.

Почему я не вижу типы файлов в своем Проводнике?

Проводник Windows (Пуск—Программы—Стандартные—Проводник) по умолчанию имеет режим, когда расширения имен (типы) файлов на экран не выводятся, но при этом выводятся значки (иконки) файлов.

Подробнее о том, как «заставить» Windows показывать типы файлов: Изменение имени файла в Windows

Выбор типа файла при сохранении файла

При сохранении файла достаточно написать его имя и выбрать тип файла из имеющегося списка. Выбранное расширение автоматически добавится к имени файла. Например, на рисунке ниже к имени файла программа сама добавит расширение .jpg. В результате Windows запомнит этот файл с именем «рисунок в paint.jpg».

выбор типа файла при его сохранении

Прежде чем сохранить файл, выбираем сначала подходящий тип файла, затем вводим имя файла и жмем «Сохранить».

Во избежание недоразумений при сохранении файлов всегда обращайте внимание на строку «тип файла», если она есть. Ведь тип файла является для Windows подсказкой, с помощью которого система определяет, какой именно программой этот файл можно открыть.

Тесная связь между типом файла и программой, открывающей такой тип

Если Вы скачали из Интернета файл, например, с расширением .rar, но на вашем компьютере не установлена программа-архиватор для работы с такими «сжатыми, заархивированными» файлами, то не удивляйтесь, что файл не открывается. Другими словами, надо отдавать себе отчет, что если открывать файлы, например, в видео-формате, то на компьютере должна быть в наличии соответствующая программа для работы с таким форматом.

Можно провести аналогию между файлом (точнее, между типом файла) и программой, работающей с таким типом файлов. Файл – замок, а программа, открывающая этот файл, –  ключик к замочку. Как известно, замок без ключика не открывается, да и ключик без замка особой ценности не представляет.

Упражнения по компьютерной грамотности:

1) Попробуйте на Рабочем столе создать две папки с именами: PRIMER и primer.

Для этого на Рабочем столе кликните правой кнопкой мыши на свободном месте, а в  появившемся окне – по опции «Создать» и, наконец, клик по опции «Папку». Вместо слов «Новая папка» введите «PRIMER». Затем все это повторяете для создания второй папки с именем «primer». Windows дал Вам «добро» на открытие второй папки?

2) Зайдите, например, в редактор Word и попробуйте сохранить документ с именем PRN. Windows разрешил такое имя для нового файла?

3) Как решить проблему: «С инета скачиваю файлы, а они в формате .rar и на компе не открываются,  не читаются. Что делать?»

Если у Вас есть вопросы по этой теме, напишите их ниже, в комментариях, я отвечу.

Дополнительно:

1. Физические и логические диски

2. Папки и файлы Windows 7

3. Как в папке расположить файлы в нужном порядке

4. 6 форматов графических файлов на сайтах

5. Сказка про Главный файл

Получайте актуальные статьи по компьютерной грамотности прямо на ваш почтовый ящик.
Уже более 3.000 подписчиков

.

Важно: необходимо подтвердить свою подписку! В своей почте откройте письмо для активации и кликните по указанной там ссылке. Если письма нет, проверьте папку Спам.

Снимок экрана командной оболочки Windows, показывающий имена файлов в каталоге Список имен файлов с длинными именами файлов, иностранные буквы, запятые, точки и пробелы, как они появляются в программном обеспечении, отображающем имена файлов

A имя файла или имя файла — имя, используемое для однозначной идентификации компьютерного файла, хранящегося в файловая система . Различные файловые системы накладывают разные ограничения на длину файлов и допустимые символы в именах файлов.

Имя файла может включать один или несколько из следующих компонентов:

  • хост (или сервер ) — сетевое устройство, содержащее файл
  • устройство (или диск ) — аппаратное устройство или диск
  • каталог (или путь ) — дерево каталогов (например, / usr / bin , TEMP, [USR.LIB.SRC]и т. Д.)
  • файл — базовое имя файла
  • типа (формат или extension ) — указывает тип содержимого файла (например, .txt, .exe, .COMи т. д.)
  • версия — номер версии или поколения файла

Компоненты, необходимые для идентификации файла, различаются в разных операционных системах, как и синтаксис и формат допустимого имени файла.

Обсуждение имен файлов осложняется отсутствием стандартизации термина. Иногда «имя файла» используется для обозначения полного имени, например, имени Windows c: directory myfile.txt. Иногда он будет использоваться для ссылки на компоненты, поэтому имя файла в этом случае будет myfile.txt. Иногда это ссылка, исключающая расширение, поэтому имя файла будет просто myfile.

Содержание

  • 1 История
    • 1.1 Миграция Unicode
  • 2 Ссылки: абсолютное и относительное
  • 3 Количество имен в файле
  • 4 Ограничения длины
  • 5 Расширения имен файлов
  • 6 Кодировка совместимость
    • 6.1 Взаимодействие индикации кодирования
    • 6.2 Взаимодействие Unicode
    • 6.3 Перспективы
  • 7 Уникальность
  • 8 Сохранение регистра букв
  • 9 Зарезервированные символы и слова
    • 9.1 В Windows
  • 10 Сравнение ограничений имени файла
  • 11 См. также
  • 12 Ссылки
  • 13 Внешние ссылки

История

Примерно в это же время появилась точка (точка или точка) в качестве разделителя расширений имени файла, и ограничение до трех буквенных расширений могло происходить из-за ограничений кодировки символов 16-бит RAD50.

Традиционно большинство операционных систем поддерживали имена файлов только с верхним регистром буквенно-цифровые символы, но с течением времени количество разрешенных символов увеличивалось. Это приводило к проблемам совместимости при перемещении файлов между разными файловыми системами.

В 1985 году RFC 959 официально определил путь как строку символов, которая должна быть введена в файловую систему пользователем. для идентификации файла.

Примерно в 1995 г. VFAT, расширение файловой системы MS-DOS FAT, было введено в Windows 95 и Windows NT. Он допускал использование длинных имен файлов (LFN) в смешанном регистре Юникода в дополнение к классическим именам «8.3».

Перенос Unicode

Одной из проблем был переход на Unicode. Для этой цели несколько компаний-разработчиков программного обеспечения предоставили программное обеспечение для переноса имен файлов в новую кодировку Unicode.

  • Microsoft предоставила прозрачную для пользователя миграцию в рамках технологии vfat
  • Apple предоставила «Утилиту восстановления кодировки имен файлов v1.0».
  • Сообщество Linux предоставило «convmv ”.

Mac OS X 10.3 ознаменовала принятие Apple декомпозиции символов Unicode 3.2, заменившей использовавшуюся ранее декомпозицию Unicode 2.1. Это изменение вызвало проблемы у разработчиков, пишущих программное обеспечение для Mac OS X.

Ссылки: абсолютные и относительные

Абсолютные ссылки включают все уровни каталогов. В некоторых системах ссылка на имя файла, которая не включает полный путь к каталогу, по умолчанию указывает на текущий рабочий каталог. Это относительная ссылка. Одним из преимуществ использования относительной ссылки в файлах конфигурации программы или сценариях является то, что разные экземпляры сценария или программы могут использовать разные файлы.

Таким образом абсолютный или относительный путь состоит из последовательности имён файлов.

Количество имен на файл

Unix-подобные файловые системы позволяют файлу иметь более одного имени; в традиционных файловых системах в стиле Unix это имена жестких ссылок на индексный дескриптор файла или его эквивалент. Windows поддерживает жесткие ссылки в файловых системах NTFS и предоставляет команду fsutilв Windows XP и mklinkв более поздних версиях для их создания. Жесткие ссылки отличаются от ярлыков Windows , классических Mac OS / ​​macOS псевдонимов или символических ссылок. Введение LFN с VFAT позволило использовать псевдонимы файлов. Например, longfi ~ 1. ???с максимум восемью плюс тремя символами был псевдонимом имени файла «длинное имя файла. ???» как способ соответствия 8.3 ограничения для старых программ.

Это свойство использовалось алгоритмом команды перемещения, который сначала создает второе имя файла, а затем удаляет только первое имя файла.

Другие файловые системы, по замыслу, предоставляют только одно имя файла для каждого файла, что гарантирует, что изменение файла с одним именем файла не изменит файл с другим именем.

Ограничения длины

Некоторые файловые системы ограничивают длину имен файлов. В некоторых случаях эта длина применяется ко всему имени файла, например, 44 символа в IBM S / 370. В других случаях ограничения длины могут применяться к определенным частям имени файла, таким как имя файла в каталоге или имя каталога. Например, 9 (например, 8-битная FAT в Standalone Disk BASIC ), 11 (например, FAT12, FAT16, FAT32 в DOS), 14 (например, ранняя версия Unix), 21 (Human68K ), 31, 30 (например, Apple DOS 3.2 и 3.3), 15 (например, Apple ProDOS ), 44 (например, IBM S / 370) или 255 (например, ранняя версия Berkeley Unix) символа или байта. Ограничения длины часто возникают в результате выделения фиксированного пространства в файловой системе для хранения компонентов имен, поэтому увеличение ограничений часто требует несовместимого изменения, а также резервирования большего пространства.

Особая проблема файловых систем, которые хранят информацию во вложенных каталогах, заключается в том, что можно создать файл с полным путем, превышающим ограничения реализации, поскольку проверка длины может применяться только к отдельным частям имени, а не к все имя. Многие приложения Windows ограничены значением MAX_PATH, равным 260, но имена файлов Windows могут легко превысить этот предел [1].

Расширения имен файлов

Многие файловые системы, включая FAT, NTFS и VMS разрешают расширение имени файла , которое состоит из одного или нескольких символов, следующих за последней точкой в ​​имени файла, разделение имени файла на две части: базовое имя или основу и расширение или суффикс, используемый некоторыми приложениями для обозначения типа файла . Несколько выходных файлов, созданных приложением, используют одно и то же базовое имя и разные расширения. Например, компилятор может использовать расширение FORдля исходного входного файла (для кода Fortran), OBJдля вывода объекта и LSTдля листинга. Хотя есть некоторые общие расширения, они произвольны, и другое приложение может использовать RELи RPT. В файловых системах, которые не разделяют расширения, файлы часто имеют более длинные расширения, такие как html.

Совместимость кодирования

Не существует общего стандарта кодирования для имен файлов.

Поскольку имена файлов должны обмениваться между программными средами (например, передача файлов по сети, хранилище файловой системы, программное обеспечение для резервного копирования и синхронизации файлов, управление конфигурацией, сжатие и архивирование данных и т. Д.), Очень важно не терять информацию об имени файла между приложениями. Это привело к широкому внедрению Unicode в качестве стандарта для кодирования имен файлов, хотя устаревшее программное обеспечение могло не поддерживать Unicode.

Взаимодействие индикации кодирования

Традиционно, имена файлов допускали использование любых символов в именах файлов, если они были безопасными для файловой системы. Хотя это позволяло использовать любую кодировку и, таким образом, позволяло представлять любой локальный текст в любой локальной системе, это вызывало множество проблем совместимости.

Имя файла может быть сохранено с использованием разных байтовых строк в разных системах внутри одной страны, например, если в одной из них используется японская кодировка Shift JIS и японская кодировка EUC. Преобразование было невозможно, так как большинство систем не отображали описание кодировки, используемой для имени файла, как часть расширенной информации о файле. Это заставляло дорогостоящее угадывать кодировку имени файла при каждом доступе к файлу.

Решением было принять Unicode в качестве кодировки для имен файлов.

Однако в классической Mac OS кодировка имени файла хранилась с атрибутами имени файла.

Совместимость с Unicode

Стандарт Unicode решает проблему определения кодировки.

Тем не менее, остаются некоторые ограниченные проблемы совместимости, такие как нормализация (эквивалентность) или используемая версия Unicode. Например, UDF ограничен Unicode 2.0; В файловой системе macOS HFS + применяется нормализация NFD Unicode и, возможно, учитывается регистр (по умолчанию регистр не учитывается). Максимальная длина имени файла нестандартна и может зависеть от размера единицы кода. Хотя это серьезная проблема, в большинстве случаев она ограничена.

В Linux это означает, что имени файла недостаточно для открытия файла: кроме того, точное байтовое представление имени файла на устройстве хранения необходим. Это может быть решено на уровне приложения с помощью некоторых сложных вызовов нормализации.

Проблема эквивалентности Unicode известна как «конфликт нормализованных имен». Решением является ненормализующая осведомленность о композиции Unicode, используемая в технических сообществах Subversion и Apache. Это решение не нормализует пути в репозитории. Пути нормализованы только для сравнения. Тем не менее, некоторые сообщества запатентовали эту стратегию, запрещая ее использование другими сообществами.

Перспективы

Чтобы ограничить проблемы взаимодействия, некоторые идеи, описанные Sun, заключаются в следующем:

  • использовать одну кодировку Unicode ( например, UTF-8)
  • выполнять прозрачное преобразование кода для имен файлов
  • не хранить нормализованные имена файлов
  • проверять каноническую эквивалентность между именами файлов, чтобы избежать двух канонически эквивалентных имен файлов в одном и том же каталог.

Эти соображения создают ограничение, не позволяющее переключиться на будущую кодировку, отличную от UTF-8.

Уникальность

В пределах одного каталога имена файлов должны быть уникальными. Поскольку синтаксис имени файла также применяется к каталогам, невозможно создать файлы и записи каталога с одинаковыми именами в одном каталоге. Несколько файлов в разных каталогах могут иметь одно и то же имя.

Подход к уникальности может различаться как в зависимости от регистра, так и в форме нормализации Unicode, например NFC, NFD. Это означает, что могут быть созданы два отдельных файла с одним и тем же текстовым именем файла и разной байтовой реализацией имени файла, например L » x00C0.txt» (UTF-16, NFC) (латинская заглавная A с могилой) и L » x0041 x0300.txt «(UTF-16, NFD) (латинская заглавная A, объединение могил).

Сохранение регистра букв

Некоторые файловые системы, такие как FAT, хранят имена файлов в верхнем регистре, независимо от того, какой регистр букв использовался для их создания. Например, файл, созданный с именем «MyName.Txt» или «myname.txt», будет сохранен с именем «MYNAME.TXT». Для обозначения одного и того же файла можно использовать любые вариации верхнего и нижнего регистра. Такие файловые системы называются без учета регистра и не с сохранением регистра . Некоторые файловые системы вообще запрещают использование строчных букв в именах файлов.

Некоторые файловые системы хранят имена файлов в том виде, в котором они были изначально созданы; они называются с сохранением регистра или с сохранением регистра . Такая файловая система может быть с учетом регистра или без учета регистра . Если учитывается регистр, то «MyName.Txt» и «myname.txt» могут относиться к двум разным файлам в одном каталоге, и при ссылке на каждый файл необходимо указывать тот же регистр, которым он назван. С другой стороны, в файловой системе без учета регистра и с сохранением регистра только одно из «MyName.Txt», «myname.txt» и «Myname.TXT» может быть именем файла в заданном каталоге в заданное время, и на файл с одним из этих имен можно ссылаться, используя любую заглавную букву имени.

С самого начала Unix и производные от нее системы сохраняли регистр. Однако не все Unix-подобные файловые системы чувствительны к регистру; по умолчанию HFS + в macOS не чувствителен к регистру, а серверы SMB обычно обеспечивают нечувствительность к регистру (даже если базовая файловая система чувствительна к регистру, например, Samba в большинстве Unix-подобных систем), а клиентские файловые системы SMB обеспечивают нечувствительность к регистру. Файловая система чувствительность к регистру представляет собой серьезную проблему для программного обеспечения, такого как Samba и Wine, которое должно эффективно взаимодействовать с обеими системами, которые обрабатывают файлы в верхнем и нижнем регистре как разные, и с системами, которые обрабатывают их как то же самое.

Зарезервированные символы и слова

Файловые системы не всегда предоставляют один и тот же набор символов для создания имени файла. До того, как Unicode стал стандартом де-факто, файловые системы в основном использовали набор символов, зависящий от локали. Напротив, некоторые новые системы допускают, чтобы имя файла состояло практически из любого символа из репертуара Unicode и даже некоторых последовательностей байтов, отличных от Unicode. Ограничения могут быть наложены файловой системой, операционной системой, приложением или требованиями к взаимодействию с другими системами.

Многие утилиты файловой системы запрещают управляющие символы появляться в именах файлов. В Unix-подобных файловых системах запрещены нулевой символ и разделитель путей /.

В Windows

Утилиты файловой системы и соглашения об именах в Windows запрещают использование определенных символов в именах файлов:

Символ Имя Причина запрета
/ косая черта Используется в качестве разделителя компонентов имени пути в Unix-подобных системах, Windows и Amiga. (Пока для параметра SwitChar установлено значение ‘/’, оболочка DOS COMMAND.COM будет использовать его как символ переключения, но сами DOS и Windows всегда принимают его как разделитель на уровне API.). Большой знак (кодовая точка Unicode U + 29F8) разрешен в именах файлов Windows.
обратная косая черта Используется в качестве разделителя компонентов имени пути по умолчанию в DOS, OS / 2 и Windows (даже если для SwitChar установлено значение ‘-‘; разрешено в именах файлов Unix, см. Примечание 1).. Большой обратный знак permitted (U + 29F9) разрешен в именах файлов Windows.
? вопросительный знак Используется как подстановочный знак в Unix, Windows и AmigaOS ; отмечает одиночный символ. Допускается в именах файлов Unix, см. Примечание 1.. заглушка голосовой щели ʔ (U + 0294), интерробанг ‽ (U + 203D), перевернутый вопросительный знак ¿(U + 00BF) и двойной вопросительный знак ⁇ (U + 2047) разрешены во всех именах файлов.
% процент Используется как подстановочный знак в RT-11 ; отмечает один символ. Не особо в Windows.
* asterisk. или звездочка Используется как подстановочный знак в Unix, DOS, RT-11, VMS и Windows. Отмечает любую последовательность символов (Unix, Windows, DOS) или любую последовательность символов в базовом имени или расширении (таким образом, «*. *» В DOS означает «все файлы». Разрешено в именах файлов Unix, см. Примечание 1.. Оператор звездочка * (U + 2217) разрешен в именах файлов Windows
: двоеточие Используется для определения точки монтирования / диска в Windows; используется для определения виртуального устройства или физического устройства, такого как диск на AmigaOS, RT-11 и VMS; используется в качестве разделителя путей в классической Mac OS. Удваивается после имени в VMS, указывает имя узла DECnet (эквивалент NetBIOS (Windows сети) имя хоста, которому предшествует «\».). Двоеточие также используется в Windows для отделения альтернативного потока данных от основного файла.. Буквенное двоеточие ꞉ (U + A789) и символ соотношения ∶ (U + 2236) разрешены в именах файлов Windows. В шрифте Segoe UI, используемом в Проводнике Windows, глифы для двоеточия и буквы двоеточия идентичны.
| по вертикали bar. или pipe Обозначает конвейерную обработку программного обеспечения в Unix, DOS и Windows; разрешено в именах файлов Unix, см. Примечание 1. стоматологический щелчок ǀ (U + 01C0) разрешен в именах файлов Windows.
" прямая двойная кавычка Одинарные кавычки ‘(U + 0027) и ’(U + 2019) и изогнутые двойные кавычки« (U + 201C) и »(U + 201D) разрешены в любом месте в именах файлов. См. Примечание 1.
< меньше чем Используется для перенаправления ввода, разрешено в именах файлов Unix, см. Примечание 1.
> больше чем Используется для перенаправления output, разрешено в именах файлов Unix, см. Примечание 1.
. точка. или точка Разрешены, но последнее вхождение будет интерпретироваться как разделитель расширений в VMS, DOS и Windows. В других операционных системах это обычно рассматривается как часть имени файла, и может быть разрешено более одной точки (точка). В Unix начальная точка означает, что файл или папка обычно скрыты.
, запятая Разрешена, но рассматривается как разделитель интерпретаторами командной строки COMMAND.COM и CMD.EXE в DOS и Windows.
; точка с запятой Допускается, но обрабатывается как разделитель интерпретаторами командной строки COMMAND.COM и CMD.EXE в DOS и Windows.
= = знак Разрешено, но обрабатывается как разделитель интерпретаторами командной строки COMMAND.COM и CMD.EXE в DOS и Windows.
пробел. Допускается, но пробел также используется как разделитель параметров в приложениях командной строки. Это можно решить, указав полное имя файла.

Примечание 1. Хотя они разрешены в именах файлов и папок Unix, для большинства оболочек Unix требуются определенные символы, такие как пробелы, <,>, |, , а иногда:, (,),,;, #, а также подстановочные знаки, такие как? и *, в кавычки или экранированный :

пять и шесть (пример экранирования). 'пять и шесть или "пять и шесть (примеры цитирования)

Символ 0xE5не разрешался в качестве первой буквы в имени файла в 86-DOS и MS-DOS / PC DOS 1.x- 2.x, но может использоваться в более поздних версиях.

В утилитах Windows пробел и точка не допускаются в качестве последнего символа имени файла. Точка допускается в качестве первого символа, но в некоторых Windows приложения, такие как Проводник Windows, запрещают создание или переименование таких файлов (несмотря на то, что это соглашение используется в Unix-подобных системах для описания скрытых файлов и каталогов). Обходные пути включают добавление точки, когда переименование файла (который впоследствии автоматически удаляется) с использованием альтернативных файловых менеджеров , создание файла с помощью командной строки или сохранение файла с желаемым именем из приложения.

Некоторые файловые системы в данной операционной системе tem (особенно файловые системы, изначально реализованные в других операционных системах) и определенные приложения в этой операционной системе могут применять дополнительные ограничения и интерпретации. Подробнее об ограничениях см. сравнение файловых систем.

В Unix-подобных системах, DOS и Windows имена файлов "." и ".." имеют особое значение (текущий и родительский каталог соответственно). Windows 95/98 / ME также использует имена типа «...», «....» и т. Д. Для обозначения каталогов прародителей или прародителей. Все версии Windows запрещают создание имен файлов, состоящих только из точек, хотя имена, состоящие из трех точек («...») или более, допустимы в Unix.

Кроме того, в утилитах Windows и DOS некоторые слова также зарезервированы и не могут использоваться в качестве имен файлов. Например, DOS файлы устройств :

CON, PRN, AUX, CLOCK $, NUL COM1, COM2, COM3, COM4, ​​COM5, COM6, COM7, COM8, COM9 LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9 LST (только в 86-DOS и DOS 1.xx) KEYBD $, SCREEN $ (только в многозадачности MS-DOS 4.0 ) $ IDLE $ (только в Concurrent DOS 386, Multiuser DOS и DR DOS 5.0 и выше) CONFIG $ (только в MS-DOS 7.0-8.0)

Системы с этими ограничениями вызывают несовместимость с некоторыми другими файловыми системами. Например, Windows не сможет обработать или создать отчеты об ошибках для этих допустимых имен файлов UNIX: aux.c, q "uote" s.txt или NUL.txt.

Имена файлов NTFS, которые используются внутри, включают:

$ Mft, $ MftMirr, $ LogFile, $ Volume, $ AttrDef, $ Bitmap, $ Boot, $ BadClus, $ Secure, $ Upcase, $ Extend, $ Quota, $ ObjId и $ Reparse

Сравнение ограничений имени файла

Система Регистр. с учетом Регистр. с сохранением Допустимый набор символов Зарезервированные символы Зарезервированные слова Максимальная длина (символы) Комментарии
8-битная FAT ? ? 7-битный ASCII (но хранится в байтах) первый символ не может быть 0x00 или 0xFF 9 Максимальный предел базового имени 9 символов для последовательных файлов (без расширения) или максимум 6- и 3-символьное расширение для двоичных файлов; см. 6.3 имя файла
FAT12, FAT16, FAT32 Нет Нет любое SBCS / DBCS OEM-кодовая страница 0x00-0x1F 0x7F "* /: <>? | +,.; = [] (В некоторых средах также:! @; DOS 1 / 2 не допускает 0xE5 в качестве первого символа) Имена устройств, включая: $ IDLE $ AUX COM1… COM4 CONFIG $ CLOCK $ KEYBD $ LPT1… LPT4 LST NUL PRN SCREEN $ (в зависимости от AVAILDEV статус везде или только в виртуальном каталоге DEV ) 11 Максимальное количество символов в базовом имени 8 и расширение 3 символа; см. 8.3 filename
VFAT Нет Да Unicode, с использованием UCS-2 кодировки 0x00-0x1F 0x7F "* /: <>? | 255
exFAT Нет Да Unicode, используя UTF-16 кодировку 0x00-0x1F 0x7F "* /: <>? | 255
NTFS Необязательно Да Unicode, с использованием UTF-16 кодировки 0x00-0x1F 0x7F "* /: <>? | Только в корневом каталоге: $ AttrDef $ BadClus $ Bitmap $ Boot $ LogFile $ MFT $ MFTMirr pagefile.sys $ Secure $ UpCase $ Volume $ Extend $ Extend $ ObjId $ Extend $ Quota $ Extend $ Повторная обработка ($ Extend - это каталог) 255 Пути могут содержать до 32000 символов.

Запрещает использование символов в диапазоне 1-31 (0x01-0x1F) и символов "* /: <>? |, Если имя не помечено как находящееся в пространстве имен Posix. NTFS разрешает каждый компонент пути (каталог или имя файла) должно состоять из 255 символов.

Windows запрещает использование имен устройств MS-DOS AUX, CLOCK $, COM1,…, COM9, CON, LPT1,…, LPT9, NUL и PRN, а также как эти имена с любым расширением (например, AUX.txt), за исключением случаев использования длинных путей UNC (например, \. C: nul.txt или \? D: aux con). (CLOCK $ может использоваться, если предоставляется расширение.) Win32 API удаляет конечную точку (точку), а также начальные и конечные пробелы из имен файлов, за исключением случаев, когда используются пути UNC. Эти ограничения применяются только к Windows; в дистрибутивах Linux, которые поддержка NTFS, имена файлов записываются с использованием пространства имен NTFS Posix, которое допускает любые символы Unicode, кроме / и NUL.

OS / 2 HPFS Нет Да любые 8 -битовый набор | ? * <":>/ 254
Mac OS HFS Нет Y es любой 8-битный набор : 255 старые версии Finder ограничены 31 символом
Mac OS HFS + Необязательно Да Unicode, с использованием кодировки UTF-16 : на диске, в классической Mac OS и на уровне Carbon в macOS; / на уровне Unix в macOS 255 Mac OS 8.1 - macOS
большинство UNIX файловых систем Да Да любой 8-битный набор / null 255 ведущий . указывает, что ls и файловые менеджеры не будут отображать файл по умолчанию
z / OS классическая файловая система MVS (наборы данных) Нет Нет Кодовые страницы EBCDIC кроме $ # @ - x'C0 ' 44 первый символ должен быть алфавитным или национальным ($, #, @)

"Qualified" содержит .после каждых 8 символов или меньше. Наборы данных с разделами (PDS или PDSE) делятся на элементы с именами до 8 символов; имя члена помещается в скобки после имени PDS, например PAYROLL.DEV.CBL (PROG001)

Файловая система CMS Нет Нет Кодовые страницы EBCDIC 8 + 8 Одноуровневый каталог структура с дисковыми буквами (A – Z). Имя файла не более 8 символов, тип файла не более 8 символов, разделенных пробелом. Например, текстовый файл с именем MEMO на диске A будет доступен как «MEMO TEXT A». (В более поздних версиях VM были представлены иерархические структуры файловой системы, SFS и BFS, но исходная плоская структура «минидисков» до сих пор широко используется.)
ранняя UNIX (ATT Corporation ) Да Да любой 8-битный набор / 14 ведущий . указывает на «скрытый» файл
POSIX «Полностью переносимые имена файлов» Да Да A – Z a – z 0–9. _ - / null 14 дефис не должен быть первым символом
ISO 9660 Нет ? A – Z 0–9 _. «близко к 180» (уровень 2) или 200 (уровень 3) Используется на компакт-дисках; макс.8 уровней каталогов (для уровня 1, не уровня 2,3)
Amiga OFS Нет Да любые 8-битные set : / null 30 Исходная файловая система 1985
Amiga FFS Нет Да любой 8-битный set : / null 30 Fast File System 1988
Amiga PFS Нет Да любой 8-битный set : / null 107 Профессиональная файловая система 1993
Amiga SFS Нет Да любой 8-битный набор : / null 107 Smart File System 1998
Amiga FFS2 Нет Да любой 8-битный набор : / null 107 Fast File System 2 2002
BeOS BFS Да Да Unicode, с использованием кодировки UTF-8 / 255
DEC PDP-11 RT-11 Нет Нет RADIX-50 6 + 3 Плоская файловая система с нет субдира. Полная «спецификация файла» включает устройство, имя файла и расширение (тип файла) в формате: dev: filnam.ext.
DEC VAX VMS Нет Начиная с. v7.2 A – Z 0–9 $ - _ 32 на компонент; ранее 9 на компонент; в последнее время 255 для имени файла и 32 для расширения. полная «спецификация файла» включает имя узла, имя диска, каталог / и, имя файла, расширение и версию в формате: OURNODE :: MYDISK: [THISDIR.THATDIR] FILENAME.EXTENSION; 2 Каталоги могут идти только 8 уровни глубокие.
Commodore DOS Да Да любой 8-битный набор :, = $ 16 длина зависит от диск, обычно 16
HP 250 Да Да любой 8-битный набор SPACE ",: NULL CHR $ (255) 6 К дискам и ленточным накопителям обращаются либо с помощью метки (до 8 символов), либо с помощью спецификации устройства. Файловая система HP 250 не использует каталоги и не использует расширения для обозначения типа файла. Вместо этого тип является атрибутом (например, DATA, PROG, BKUP или SYST для файлов данных, программных файлов, резервных копий и самой ОС).

См. Также

  • Файловая система
  • Полное имя файла
  • Длинное имя файла
  • Путь (вычисление)
  • Слаг (веб-публикация)
  • Символьная ссылка
  • Унифицированный идентификатор ресурса (URI)
  • Унифицированный указатель ресурса (URL) и интернационализированный идентификатор ресурса

Ссылки

  1. ^ Дэвид Робинсо; Йенуп Сун; Николас Уильямс (март 2006 г.). «Презентации Solaris: файловые системы, Unicode и нормализация» (PDF). Сан-Франциско: Su n.com. Архивировано (PDF) из оригинала 4 июля 2012 г.
  2. ^RFC 959 IETF.org RFC 959, протокол передачи файлов (FTP)
  3. ^«Утилита восстановления кодировки имен файлов v1.0». Support.apple.com. 1 июня 2006 г. Получено 2 октября 2018 г.
  4. ^"convmv - конвертирует имена файлов из одной кодировки в другую". J3e.de. Проверено 17 сентября 2013 г.
  5. ^«Re: git на MacOSX и файлы с разложенными именами файлов utf-8». KernelTrap. 7 мая 2010 г. Архивировано с исходного 15 марта 2011 г. Получено 5 июля 2010 г.
  6. ^«Страница описания команды Fsutil». Microsoft.com. Получено 15 сентября 2013 г.
  7. ^«Жесткие ссылки NTFS, ссылки на каталоги и ярлыки Windows». Гибкий шестигранник. Inv Softworks. Проверено 12 марта 2011 г.
  8. ^ "Поддержка ddname с FTP, z / OS V1R11.0 Communications Server IP. Руководство пользователя и команды z / OS V1R10.0-V1R11.0 SC31-8780-09". IBM.com.
  9. ^"Имена файлов с диакритическими знаками". Нед Батчелдер. Получено 17 сентября 2013 г.
  10. ^"NonNormalizingUnicodeCompositionAwareness - Subversion Wiki". Wiki.apache.org. 21 января 2013 г. Получено 17 сентября 2013 г.
  11. ^«Соглашения об именах межплатформенных путей к файлам - общее программирование». GameDev.net. Получено 17 сентября 2013 г.
  12. ^"CaseInsensitiveFilenames - The Official Wine Wiki". Wiki.winehq.org. 8 ноября 2009 г. Архивировано с оригинала 18 августа 2010 г. Получено 20 августа 2010 г.
  13. ^«Проблема 6 базовых спецификаций открытой группы». IEEE Std 1003.1-2001. Открытая группа. 2001.
  14. ^«Именование файлов, путей и пространств имен (Windows)». Msdn.microsoft.com. 26 августа 2013 г. Получено 17 сентября 2013 г.
  15. ^«Соглашения об именах Windows». MSDN, Microsoft.com. См. Последний отмеченный пункт.
  16. ^ Именование файла msdn.microsoft.com (MSDN), ограничения имени файла в Windows
  17. ^Microsoft Windows 95 README for Tips and Tricks, Microsoft, получено 27 августа 2015 г.
  18. ^MS-DOS Имена драйверов устройств не могут использоваться в качестве имен файлов., Microsoft
  19. ^ Именование файлов, путей и пространств имен, Microsoft
  20. ^Риттер, Гуннар (30 января 2007 г.). "Сказка о" aux.c "". Heirloom Project.
  21. ^«Определение субпараметра, z / OS V1R11.0 MVS JCL Reference». IBM.com. Получено 17 сентября 2013 г.
  22. ^Левин, Дональд. Руководство программиста POSIX: Написание переносимых программ UNIX 1991 O'Reilly Associates, Inc. Севастополь, Калифорния, стр. 63-64
  23. ^Hewlett-Packard Company Roseville, CA Справочник по синтаксису HP 250 Ред. 1/84 Руководство Номер детали 45260-90063

Внешние ссылки

Найдите имя файла или имена файлов в Wiktionary, бесплатном словаре.
  • Форматы данных Имя файла at Curlie
  • Библиотека расширений файлов
  • FILExt
  • WikiExt - Энциклопедия расширений файлов
  • Именование файлов, путей и пространств имен (MSDN)
  • Набор символов переносимого имени файла POSIX 2009
  • Стандартный ECMA -208, декабрь 1994 г., Системно-независимый формат данных
  • Лучшие методы именования файлов, США: Библиотеки Стэнфордского университета, Службы управления данными

.

Понравилась статья? Поделить с друзьями:
  • Разные языки в разных окнах windows 10
  • Разрешения на установку системных служб windows 10
  • Размытые буквы на мониторе windows 10
  • Разные фоновые рисунки на двух мониторах windows 10
  • Разрешения каталога данных службы поиска windows nt authority система