Search code examples
pathbackslashslashpath-separator

Difference between forward slash (/) and backslash (\) in file path


I was wondering about the difference between \ and / in file paths. I have noticed that sometimes a path contains /and sometimes it is with \.

It would be great if anyone can explain when to use \ and /.


Solution

  • / is the path separator on Unix and Unix-like systems. Modern Windows can generally use both \ and / interchangeably for file paths, but Microsoft has advocated for the use of \ as the path separator for decades.

    This is done for historical reasons that date as far back as the 1970s, predating Windows by over a decade. In the beginning, MS-DOS (the foundation to early Windows) didn't support directories. Unix had directory support using the / character since the beginning. However, when directories were added in MS-DOS 2.0, Microsoft and IBM were already using the / character for command switches, and because of DOS's lightweight parser (descended from QDOS and designed to run on lower end hardware), they chose to use a new character rather than risk breaking compatibility with their existing applications.

    So, to avoid errors about "missing a switch" or "invalid switch" when passing file paths as arguments to commands such as these:

    cd/                        <---- no switch specified
    dir folder1/folder2        <---- /folder2 is not a switch for dir
    

    it was decided that the \ character would be used instead, so you could write those commands like this

    cd\
    dir folder1\folder2
    

    without error.

    Later, Microsoft and IBM collaborated on an operating system unrelated to DOS called OS/2. OS/2 had the ability to use both separators, probably to attract more Unix developers. When Microsoft and IBM parted ways in 1990, Microsoft took what code they had and created Windows NT, on which all modern versions of Windows are based, carrying this separator agnosticism with it.


    As backward compatibility has been the name of the game for Microsoft from all of the major OS transitions that they've undertaken (DOS to Win16/DOS, to Win16/Win32, to Win32/WinNT), this peculiarity stuck, and it will probably exist for a while yet.

    It's for this reason that this discrepancy exists. It should really have no effect on what you're doing because, like I said, the Windows API can generally use them interchangeably. However, 3rd party applications (and even many of Microsoft's own for legacy reasons) may break if you pass a / when they expect a \ between directory names. If you're using Windows, stick with \. If you're using Unix or URIs (which have their foundation in Unix paths, but that's another story entirely), then use /.