Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

windows and linux discrepancy: backslash and forward slash in c++

Tags:

c++

linux

windows

In windows I have

std::string graphdir = projDir + "graph\\";
int mkdirsf=_mkdir(graphdir.c_str());

The above works quite well in windows. But in linux, you know forward slashed / are used. So the above will create a folder with name graph\. Is there an universal way to enter the correct folder without worrying about / or \?

like image 553
John Avatar asked Dec 11 '22 04:12

John


1 Answers

You might consider using forward slashes even on Windows as a directory separator. Most Windows libraries are able to convert them to backward slashes (they actually don't do a conversion, but understand them as wanted; the rest is an implementation detail)

Otherwise, notice that the C++11 (or C++14) standard don't know about "folders" (you actually mean directories; since folders are only a GUI artefact; read e.g. n3337 to check). C++17 has std::filesystem.

Maybe you should consider some other libraries or frameworks: Boost, POCO, Qt all know how to deal with directories on common OSes (Windows, Linux, MacOSX, Android).

A more significant concern is the "drive" letter. For Windows (and even some MS-DOS) C:/FOO/BAR.TXT (or, using backslashes, C:\FOO\BAR.TXT) and D:/FOO/BAR.TXT refer to different files. There is no real equivalent in Linux or MacOSX. Since mount points are more general.

At last, file hierarchy conventions (and file systems) vary widely from one OS to the other. For Linux, see hier(7) and path_resolution(7). Notice that globbing is also OS specific (and happens differently: in Unix systems, it is often done by shells; on Windows, it might be done, in every application, by some crt0 like thing of the runtime system). For Linux, see also glob(7).

BTW, perhaps you could consider using WSL on your Windows machine. In lucky cases, the same executable could run on Linux and on Windows (under WSL), and that makes your work easier (when it is usable).

Take time to read more about operating systems and file systems. I recommend the Operating System: Three Easy Pieces textbook (freely downloadable).

You could find useful to read more about your OS. For Linux, read ALP (or some newer book) then syscalls(2) and intro(3) etc... For Windows, learn the WinAPI (I don't know it), perhaps by starting here.

On Linux, the API relevant to directories include mkdir(2), chdir(2), rmdir(2), getcwd(2), stat(2), opendir(3) and closedir, readdir(3), nftw(3), etc, etc.... Be aware that a file is on Linux just an i-node (read inode(7) and about hard links) and can be in several directories (or none), see link(2). AFAIU, this makes a huge difference with Windows.

PS. I never used Windows, and never coded for it.

like image 182
Basile Starynkevitch Avatar answered Apr 28 '23 08:04

Basile Starynkevitch