Windows get system path

How to set the path and environment variables in Windows

Setting the path and environment variables will differ depending on the version of Windows you have on your computer. Choose a link below for your version of Windows.

Administrator privileges are usually required to modify the path and environment variables.

Setting the path and variables in Windows 10

  1. From the desktop, right-click the very bottom-left corner of the screen to get the Power User Task Menu.
  2. From the Power User Task Menu, click System.
  3. In the Settings window, scroll down to the Related settings section and click the System info link.
  4. In the System window, click the Advanced system settings link in the left navigation pane.
  5. In the System Properties window, click the Advanced tab, then click the Environment Variablesbutton near the bottom of that tab.
  6. In the Environment Variables window (pictured below), highlight the Path variable in the System variables section and click the Edit button. Add or modify the path lines with the paths you want the computer to access. Each different directory is separated with a semicolon, as shown below.

You can edit other environment variables by highlighting the variable in the System variables section and clicking Edit. If you need to create a new environment variable, click New and enter the variable name and variable value.

To view and set the path in the Windows command line, use the path command.

Setting the path and variables in Windows 8

  1. From the desktop, right-click the very bottom-left corner of the screen to get the Power User Task Menu.
  2. From the Power User Task Menu, click System.
  3. Click the Advanced System Settings link in the left column.
  4. In the System Properties window, click the Advanced tab, then click the Environment Variablesbutton near the bottom of that tab.
  5. In the Environment Variables window (pictured below), highlight the Path variable in the System variables section and click the Edit button. Add or modify the path lines with the paths you want the computer to access. Each different directory is separated with a semicolon, as shown below.

You can edit other environment variables by highlighting the variable in the System variables section and clicking Edit. If you need to create a new environment variable, click New and enter the variable name and variable value.

To view and set the path in the Windows command line, use the path command.

Setting the path and variables in Windows Vista and Windows 7

  1. From the desktop, right-click the Computer icon and select Properties. If you don’t have a Computer icon on your desktop, click Start, right-click the Computer option in the Start menu, and select Properties.
  2. Click the Advanced System Settings link in the left column.
  3. In the System Properties window, click the Advanced tab, then click the Environment Variablesbutton near the bottom of that tab.
  4. In the Environment Variables window (pictured below), highlight the Path variable in the System variables section and click the Edit button. Add or modify the path lines with the paths you want the computer to access. Each different directory is separated with a semicolon, as shown below.
Читайте также:  Linux проверка диска xfs

You can edit other environment variables by highlighting the variable in the System variables section and clicking Edit. If you need to create a new environment variable, click New and enter the Variable name and Variable value.

To view and set the path in the Windows command line, use the path command.

Setting the path and variables in Windows 2000 and Windows XP

The path is now managed by Windows 2000 and Windows XP and not the autoexec.bat or autoexec.nt files, as was done with earlier versions of Windows. To change the system environment variables, follow the steps below.

  1. From the desktop, right-click My Computer and click Properties. If you don’t have a My Computer icon on your desktop, click Start, right-click the My Computer option in the Start menu, and select Properties.
  2. In the System Propertieswindow, click the Advancedtab.
  3. In the Advanced section, click the Environment Variablesbutton.
  4. In the Environment Variables window (as shown below), highlight the Path variable in the System Variable section and click the Edit button. Add or modify the path lines with the paths you want the computer to access. Each different directory is separated with a semicolon, as shown below.

You can edit other environment variables by highlighting the variable in the System variables section and clicking Edit. If you need to create a new environment variable, click New and enter the Variable name and Variable value.

To view and set the path in the Windows command line, use the path command.

What is the default Windows %PATH%?

The path is based on programs installed on the computer, so there is no «default path.» However, the Windows minimum path is often the path below.

Keep in mind that as you install programs, the path is updated with the paths for the newly installed programs. So, if you have erased your path after installing other programs, those programs may be affected.

Setting path in the MS-DOS and Windows command line

To view and set the path in MS-DOS and in the Windows command line, use the path command.

Навигация по файловой системе File System Navigation

Заголовок реализует техническую спецификацию файловой системы C++ ISO/IEC TS 18822:2015 (окончательный вариант черновика: ISO/IEC JTC 1/SC 22/WG 21 N4100) и имеет типы и функции, позволяющие создавать независимый от платформы код для навигации по файловой системе. The header implements the C++ File System Technical Specification ISO/IEC TS 18822:2015 (Final draft: ISO/IEC JTC 1/SC 22/WG 21 N4100) and has types and functions that enable you to write platform-independent code for navigating the file system. Поскольку это межплатформенное приложение, оно содержит интерфейсы API, не относящиеся к системам Windows. Because it’s cross-platform, it contains APIs that aren’t relevant for Windows systems. Например, is_fifo(const path&) всегда возвращает значение false в Windows. For example, is_fifo(const path&) always returns false on Windows.

Обзор Overview

Используйте API для следующих задач: Use the APIs for the following tasks:

выполнение итерации по файлам и каталогам в указанном пути; iterate over files and directories under a specified path

получение сведений о файлах, включая время создания, размер, расширение и корневой каталог; get information about files including the time created, size, extension, and root directory

составление, разделение и сравнение путей; compose, decompose, and compare paths

Создание, копирование и удаление каталогов create, copy, and delete directories

копирование и удаление файлов. copy and delete files

Дополнительные сведения о вводе-выводе файлов с помощью стандартной библиотеки см. в разделе Программирование iostream. For more information about File IO using the Standard Library, see iostream Programming.

Пути Paths

Создание и составление путей Constructing and composing paths

Пути в Windows (начиная с XP) изначально хранятся в Юникоде. Paths in Windows (since XP) are stored natively in Unicode. path Класс автоматически выполняет все необходимые преобразования строк. The path class automatically does all necessary string conversions. Он принимает аргументы как для широких, так и для узких символьных массивов, а также для std::string std::wstring типов, отформатированных как UTF8 или UTF16. It accepts arguments of both wide and narrow character arrays, and both std::string and std::wstring types formatted as UTF8 or UTF16. Класс path также автоматически нормализует разделители путей. The path class also automatically normalizes path separators. В аргументах конструктора в качестве разделителя каталогов можно использовать одиночную косую черту. You can use a single forward slash as a directory separator in constructor arguments. Этот разделитель позволяет использовать одни и те же строки для хранения путей в средах Windows и UNIX: This separator lets you use the same strings to store paths in both Windows and UNIX environments:

Читайте также:  Образ автоматической установки windows

Для объединения двух путей можно использовать перегруженные операторы / и /= , которые аналогичны операторам + и += в std::string и std::wstring . To concatenate two paths, you can use the overloaded / and /= operators, which are analogous to the + and += operators on std::string and std::wstring . path Объект будет удобным образом предоставлять разделители, если это не так. The path object will conveniently supply the separators if you don’t.

Проверка путей Examining paths

Класс Path имеет несколько методов, возвращающих сведения о различных частях пути. The path class has several methods that return information about various parts of the path itself. Эта информация отличается от сведений о сущности файловой системы, на которую может ссылаться. This information is distinct from the information about the file system entity it might refer to. Можно получить корень, относительный путь, имя файла, расширение файла и другие сведения. You can get the root, the relative path, the file name, the file extension, and more. Можно выполнять итерацию по объекту path для проверки всех папок в иерархии. You can iterate over a path object to examine all the folders in the hierarchy. В следующем примере показано, как выполнить итерацию по объекту пути. The following example shows how to iterate over a path object. И, как получить сведения о его частях. And, how to retrieve information about its parts.

Код создает следующие выходные данные: The code produces this output:

Сравнение путей Comparing paths

Класс path перегружает операторы сравнения на равенство как std::string и std::wstring . The path class overloads the same comparison operators as std::string and std::wstring . При сравнении двух путей необходимо выполнить сравнение строк после нормализации разделителей. When you compare two paths, you make a string comparison after the separators have been normalized. Если пропущена Замыкающая косая черта (или обратная косая черта), она не добавляется и влияет на сравнение. If a trailing slash (or backslash) is missing, it isn’t added, and that affects the comparison. В следующем примере показано, как выполняется сравнение значений пути: The following example demonstrates how path values compare:

Для запуска этого кода вставьте его в полный пример выше перед main и раскомментируйте строку, которая вызывает его в основном объекте. To run this code, paste it into the full example above before main and uncomment the line that calls it in main.

Преобразование между типами пути и строки Converting between path and string types

Объект path может быть неявно преобразован в std::wstring или std::string . A path object is implicitly convertible to std::wstring or std::string . Это означает, что можно передать путь к таким функциям wofstream::open , как, как показано в следующем примере: It means you can pass a path to functions such as wofstream::open , as shown in this example:

Итерация по каталогам и файлам Iterating directories and files

Заголовок предоставляет directory_iterator тип для итерации по отдельным каталогам и recursive_directory_iterator класс для рекурсивного прохода по каталогу и его подкаталогам. The header provides the directory_iterator type to iterate over single directories, and the recursive_directory_iterator class to iterate recursively over a directory and its subdirectories. После создания итератора путем передачи ему объекта path итератор указывает на первое значение directory_entry в пути. After you construct an iterator by passing it a path object, the iterator points to the first directory_entry in the path. Создайте конечный итератор путем вызова конструктора по умолчанию. Create the end iterator by calling the default constructor.

Читайте также:  Образ загрузочной флешки windows 10 чем сделать

При итерации по каталогу существует несколько типов элементов, которые можно обнаружить. When iterating through a directory, there are several kinds of items you might discover. К этим элементам относятся каталоги, файлы, символические ссылки, файлы сокетов и др. These items include directories, files, symbolic links, socket files, and others. directory_iterator Возвращает свои элементы в виде directory_entry объектов. The directory_iterator returns its items as directory_entry objects.

Path. Get Path Root Метод

Определение

Перегрузки

Получает сведения о корневом каталоге из пути, содержащегося в указанном диапазоне символов. Gets the root directory information from the path contained in the specified character span.

Получает сведения о корневом каталоге из пути, содержащегося в указанной строке. Gets the root directory information from the path contained in the specified string.

GetPathRoot(ReadOnlySpan )

Получает сведения о корневом каталоге из пути, содержащегося в указанном диапазоне символов. Gets the root directory information from the path contained in the specified character span.

Параметры

Доступная только для чтения область символов, содержащая путь, из которого нужно получить сведения о корневом каталоге. A read-only span of characters containing the path from which to obtain root directory information.

Возвращаемое значение

Диапазон символов только для чтения, содержащий корневой каталог path . A read-only span of characters containing the root directory of path .

Комментарии

Этот метод не проверяет, существует ли путь или файл. This method does not verify that the path or file exists.

В отличие от перегрузки строки, этот метод не нормализует разделители каталогов. Unlike the string overload, this method doesn’t normalize directory separators.

Значение ReadOnlySpan равно «фактически пустой», если: A ReadOnlySpan is «effectively empty» if:

  • В Windows при вызове ReadOnlySpan .IsEmpty в этом фрагменте символов возвращаются символы true , или все знаки являются пробелами («»). In Windows, calling ReadOnlySpan .IsEmpty on this span of characters returns true , or all its characters are spaces (‘ ‘).
  • В UNIX вызов ReadOnlySpan .IsEmpty для этого диапазона символов возвращает true . In Unix, calling ReadOnlySpan .IsEmpty on this span of characters returns true .

Ниже приведены возможные шаблоны для диапазона символов только для чтения, возвращаемого этим методом. Possible patterns for the read-only character span returned by this method are as follows:

ReadOnlySpan .Empty ( path указан относительный путь на текущем диске или томе). ReadOnlySpan .Empty ( path specified a relative path on the current drive or volume).

«/» (UNIX: path указан абсолютный путь на текущем диске). «/» (Unix: path specified an absolute path on the current drive).

«X:» (Windows: path указывает относительный путь на диске, где X представляет букву диска или тома). «X:» (Windows: path specified a relative path on a drive, where X represents a drive or volume letter).

«X: » (Windows: path указан абсолютный путь на заданном диске). «X:» (Windows: path specified an absolute path on a given drive).

» \ \Компутернаме\шаредфолдер» (Windows: путь UNC). «\\ComputerName\SharedFolder» (Windows: a UNC path).

» \ \ ? \C:» (Windows: путь к устройству DOS, поддерживается в .NET Core 1,1 и более поздних версиях, а в платформа .NET Framework 4.6.2 и более поздних версий). «\\?\C:» (Windows: a DOS device path, supported in .NET Core 1.1 and later versions, and in .NET Framework 4.6.2 and later versions).

Дополнительные сведения о путях к файлам в Windows см. в разделе форматы путей к файлам в системах Windows. For more information on file paths on Windows, see File path formats on Windows systems. Список общих задач ввода-вывода см. в разделе Общие задачи ввода-вывода. For a list of common I/O tasks, see Common I/O Tasks.

Оцените статью