-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilesystem.html
555 lines (458 loc) · 20.2 KB
/
filesystem.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
<!DOCTYPE html>
<html lang="en">
<head>
<title>C++17 Filesystem</title>
<link rel="stylesheet" href="Assets/Stylesheets/3rd party/bootstrap.min.css">
<link rel="stylesheet" href="Assets/Stylesheets/3rd party/prism.css">
<link rel="stylesheet" href="Assets/Stylesheets/main.css">
<script type="text/javascript" src="Assets/Scripts/3rd party/prism.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="Assets/Icons/logo.png">
<link href="https://fonts.googleapis.com/css2?family=Bad+Script&family=Bai+Jamjuree&family=Barlow+Condensed&family=Cairo:wght@600&family=Gruppo&family=Tenali+Ramakrishna&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Exo+2:wght@500&family=Yanone+Kaffeesatz&display=swap" rel="stylesheet">
</head>
<body>
<!--Navigation-->
<nav class="navbar navbar-expand-lg navbar-custom sticky-top">
<span class="navbar-brand">Technizz</span>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="index.html">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="topics.html">Topics</a>
</li>
</ul>
</div>
<a class="contact" href="https://www.linkedin.com/in/nirali-sahoo-11d2001y08m/" target="_blank" title="LinkedIn"><img src="Assets/Icons/linkedin.png" width="30" height="30" class="d-inline-block align-top" alt="" loading="lazy"></a>
<a class="contact" href="https://github.com/nizz009" target="_blank" title="Github"><img src="Assets/Icons/github.png" width="30" height="30" class="d-inline-block align-top" alt="" loading="lazy"></a>
</nav>
<!--Heading-->
<h1>Filesystem (C++17)</h1>
<!--Sections-->
<section class="sortarticle">
<h2>Introduction</h2>
<p>
So, as it can be known from the title, filesystem was first introduced in C++17. This came with many new and simplified functions and operations which reduced the many lines of code that were necessary in the previous versions of C++ (A comparison between the programs in C++11 and using C++17's filesystem is elaborated in <a href="https://carlosvin.github.io/posts/recursive-directory-iterator/en/" target="_blank">Carlos's Filesystem in C++17</a>). For a while, filesystem was not a standard C++ header. Hence, many compilers or text editors (usually the older versions) may not be able to execute the program succesfully or may require a different header file (which we shall discuss next).
</p>
<h2>Compatibility and Compilation</h2>
<p>
Did you ever stumble across two different kinds of headers (<code id="program" class="language-c++">include <experimental/filesystem></code> and <code id="program" class="language-c++">include <filesystem></code>) and wondered why there were two? Well, here's the answer:<br>(Don't worry if you haven't though. You will know all about it now:)
</p>
<p>
Back when filesystem was still a pre-standard header, compilers like GCC v6 and v7 supported the "Filesystem Technical Specification" which was defined in the <code id="program" class="language-c++"><experimental/filesystem></code> header. After it was given the status of standardized C++ header, the compilers since then supported the <code id="program" class="language-c++"><filesystem></code> header.
</p>
<p>
So, now it's time for the compilation!
</p>
<p>
Firstly, the compiler needs to know that we are using C++17. We can do so using <code id="program" class="language-c++">-c++1z</code> after calling the compiler. Secondly, with the pre-standard versions, <code id="program" class="language-c++">-lstdc++fs</code> is added at the end of the compilation command making it look like: <br> <code id="program" class="language-c++">g++ -std=c++1z main.cpp -lstdc++fs</code>
</p>
<p>
GCC v8 and higher versions support the <code id="program" class="language-c++"><filesystem></code> implementation with the <code id="program" class="language-c++">-std=c++17</code> flag.
</p>
<p>
Now, talking about the compilers other than GCC; Clang lib++ v7, MSVC Standard Library 19.14 (Visual Studio 15.7), Apple Clang 10.0.0 and Embarcadero C++ Builder 10.3 and their respective higher versions support filesystem while it has still not been a part of Cray's and Sun/Oracle's C++ standard libraries.
<h2>Functions</h2>
<p>
Now that we know how to compile our program and check if our functions are all right, let's move to the most interesting part: <i>Filesystem Functions</i> !
</p>
<p>
<h6>Note:</h6> We need to call the functions using the namespace <code id="program" class="language-c++">std::experimental::filesystem</code> (for older versions of compilers that support pre-standard filesystem header) and <code id="program" class="language-c++">std::filesystem</code> (for those supporting the standard filesystem header). So in order to reduce our efforts, we define it as: <br> <code id="program" class="language-c++">namespace fs = std::experimental::filesystem</code> <br> or <br> <code id="program" class="language-c++">namespace fs = std::filesystem</code>
</p>
<h3>Working with Paths (fs::path)</h3>
<p>
Knowing and understanding the correct path (The important parts of a file path are described in <a href="https://docs.microsoft.com/en-us/cpp/standard-library/filesystem?view=vs-2019#syntax">Microsoft's document on <filesystem> - Syntax</a>.) of the file is essential for the working of the program according to our plans and fortunately, filesystem makes it easier for us.
<ol>
<li>
<h4>Retrieving parts of file path:</h4>
<p>
<pre>
<code id="program" class="language-c++">
#include <filesystem>
#include <iostream>
#include <cstdio>
namespace fs = std::filesystem;
using namespace std;
int main()
{
fs::path filepath {"./path/to/file.txt"};
cout << "Parent path: " << filepath.parent_path() << endl;
cout << "Filename: " << filepath.filename() << endl;
cout << "Extension: " << filepath.extension() << endl;
//EXIT_SUCCESS: Defined in cstdio library - used for getting rid of machine dependent success values.
return EXIT_SUCCESS;
}
</code>
</pre>
Compiler's Output:
<pre>
<code id="program" class="language-c++">
Parent path: "./path/to"
Filename: "file.txt"
Extension: ".txt"
</code>
</pre>
</p>
</li>
<li>
<h4>Director Separators (fs::path::preferred_separator)</h4>
<p>
Director Separators are different for Microsoft Windows (\) and for POSIX (/) Operation Systems (OS). There are many ways (with and without using filesystem) to insert the director separator preffered by a certain OS but let's go through a relatively lengthier one just to prove later on how convenient filesystem is for us.
<h5>Method 1: Without the use of filesystem function</h5>
<pre>
<code id="program" class="language-c++">
#include <iostream>
#include <cstdio>
using namespace std;
//If the system is Microsoft Windows:
#ifdef _WIN32
const string SEP = "\\";
// NOTE: we use "\\" as '\' is an idicator for escape character in C++.
//For others:
#else
const string SEP = "/";
#endif
int main()
{
cout << "Directory separator in the system is: " << SEP << endl;
return EXIT_SUCCESS;
}
</code>
</pre>
<h5>Method 2: Using the filesystem operator</h5>
<pre>
<code id="program" class="language-c++">
#include <filesystem>
#include <iostream>
#include <cstdio>
namespace fs = std::filesystem;
using namespace std;
int main()
{
cout << "Directory separator in the system is: " << fs::path::preferred_separator << endl;
return EXIT_SUCCESS;
}
</code>
</pre>
Compiler's Output (for both cases):
<pre>
<code id="program" class="language-c++">
//For Windows:
Directory separator in the system is: \
//For POSIX:
Directory separator in the system is: /
</code>
</pre>
</p>
</li>
<li>
<h4>Composing Paths:</h4>
<p>
Now that we know how a path "looks" like, it's time for composing them. They can be done by:
<ul>
<li><h6>Append (/=) operator:</h6> adds path along with the directory separators</li>
<li><h6>Concat (+=) operator:</h6> only adds the string without the directory separators</li>
</ul>
<h5>Append (/=) Operator</h5>
<pre>
<code id="program" class="language-c++">
#include <filesystem>
#include <iostream>
#include <cstdio>
namespace fs = std::filesystem;
using namespace std;
int main()
{
fs::path newpath("C:\\welcome");
newpath /= "to";
newpath /= "technizz";
cout << "The new path is: " << endl << newpath << endl;
return EXIT_SUCCESS;
}
</code>
</pre>
Compiler's Output:
<pre>
<code id="program" class="language-c++">
The new path is:
C:\welcome\to\technizz
</code>
</pre>
<h5>Concat (+=) Operator:</h5>
<pre>
<code id="program" class="language-c++">
#include <filesystem>
#include <iostream>
#include <cstdio>
namespace fs = std::filesystem;
using namespace std;
int main()
{
fs::path newpath("C:\\welcome");
newpath += "to";
newpath += "technizz";
cout << "The new path is: " << endl << newpath << endl;
return EXIT_SUCCESS;
}
</code>
</pre>
Compiler's Output:
<pre>
<code id="program" class="language-c++">
The new path is:
C:\welcometotechnizz
</code>
</pre>
This can also be written in another similar way:
<pre>
<code id="program" class="language-c++">
#include <filesystem>
#include <iostream>
#include <cstdio>
namespace fs = std::filesystem;
using namespace std;
int main()
{
fs::path root {"/welcome/"};
fs::path dir {"to/"};
fs::path index {"technizz"};
fs::path newpath = root / dir / index;
cout << "The new path is: " << endl << newpath << endl;
return EXIT_SUCCESS;
}
</code>
</pre>
Compiler's Output:
<pre>
<code id="program" class="language-c++">
//Note that the directory separators were included in the root, dir and index in the program.
//This is why we get '/' in the new path too.
The new path is:
/welcome/to/technizz
</code>
</pre>
</p>
</li>
</ol>
</p>
<h3>Working with Directories</h3>
<p>
So! Now that we have enough knowledge about file paths and directories, let's have some fun with them.
<ol>
<li>
<h4>Creating Directories (create_directory, create_directories):</h4>
<p>
<h6>Return type (for both):</h6> <i>bool</i> ('true' if directory/ies is/are created, else false)
The basic concept is, creating directories which don't exist or copy the attributes of already existing directories into the new ones (OS dependent).
<br>
Unlike the previous versions of C++, C++17's filesystem again removes the need for multiple lines of code for creating (also removing) each parent directory before creating (or removing) the child directory.
<pre>
<code id="program" class="language-c++">
#include <filesystem>
#include <iostream>
#include <cstdio>
namespace fs = std::filesystem;
using namespace std;
int main()
{
fs::create_directories("It/creates/four/directories");
//prints the details of the directories created (time, date of creation, etc):
system("ls -la It/*");
return EXIT_SUCCESS;
}
</code>
</pre>
Compiler's Output:
<pre>
<code id="program" class="language-c++">
total 12
drwxr-xr-x 3 695539398 695539398 4096 Jul 9 23:52 .
drwxr-xr-x 3 695539398 695539398 4096 Jul 9 23:52 ..
drwxr-xr-x 3 695539398 695539398 4096 Jul 9 23:52 four
</code>
</pre>
</p>
</li>
<li>
<h4>Removing Directories:</h4>
<p>
We all know how easy it is to destroy things right? Well, filesystem makes removing directories as easy as (or even easier than) creating directories. Just like create_directory/create_directories, it returns a boolean value indicating whether the directories were removed or not.
<pre>
<code id="program" class="language-c++">
#include <filesystem>
#include <iostream>
#include <cstdio>
namespace fs = std::filesystem;
using namespace std;
int main()
{
//Let's assume none of the directories existed before. Hence, we create them first.
fs::create_directories("It/creates/four/directories");
//Deletes all the children directories of "It", including itself ("It")
fs::remove_all("It");
system("ls -la");
return EXIT_SUCCESS;
}
</code>
</pre>
Compiler's Output:
<pre>
<code id="program" class="language-c++">
total 40
drwx------ 2 862488388 862488388 4096 Jul 10 00:08 .
drwxr-xr-x 3 862488388 862488388 60 Jul 10 00:08 ..
-rw------- 1 862488388 862488388 452 Jul 10 00:08 prog.cc
-rwxr-xr-x 1 862488388 862488388 30256 Jul 10 00:08 prog.exe
</code>
</pre>
</p>
</li>
</ol>
</p>
<h3>Working with Files</h3>
<p>
So, we have created the directories. What's next? Of course we need something to "work on" right? So now, we will know the magic to create, write to, read from and remove files.
<ol>
<li>
<h4>Creating Files:</h4>
<pre>
<code id="program" class="language-c++">
#include <filesystem>
#include <iostream>
#include <cstdio>
#include <string>
namespace fs = std::filesystem;
using namespace std;
int main()
{
//Not-so-easy way: filepath is in form of string
string filepath;
cin >> filepath;
//converts string to file path
fs::path fpath(filepath);
//finds and creates directories upto the parent path
fs::create_directories(fpath.parent_path());
//creates the file
ofstream ofs(fpath);
ofs.close();
return EXIT_SUCCESS;
}
</code>
</pre>
</li>
<li>
<h4>Reading from a file:</h4>
<p>
Reading and writing to a file requires the use of <em>fstream</em> along with the filesystem properties.
<pre>
<code id="program" class="language-c++">
#include <filesystem>
#include <iostream>
#include <fstream>
#include <cstdio>
#include <string>
namespace fs = std::filesystem;
using namespace std;
int main()
{
string filepath s;
cin >> filepath;
//converts string to file path
fs::path fpath(filepath);
//retrieves only the file name
const string file = fpath.filename();
//opens the file in read mode
//NOTE: freopen takes a constant C-style string as it's parameter.
//Thus, the file name is converted to a C-style string.
freopen(file.c_str(), "r", stdout);
//reads the string from the file and prints it
cin >> s;
cout << s << endl;
return EXIT_SUCCESS;
}
</code>
</pre>
</p>
</li>
<li>
<h4>Writing to a file:</h4>
Writing to a file may seem a little weird at first but it's like a combination of creating and reading a file.
<pre>
<code id="program" class="language-c++">
#include <filesystem>
#include <iostream>
#include <fstream>
#include <cstdio>
#include <string>
namespace fs = std::filesystem;
using namespace std;
int main()
{
string filepath;
cin >> filepath;
//converts string to file path
fs::path fpath(filepath);
//retrieves the filename
const string file = fpath.filename();
//creates directory (if not present already)
if(!(fs::exists(filepath)))
{
fs::create_directories(fpath.parent_path());
//creates a file
ofstream ofs(path);
ofs.close();
}
//opens the file in write mode
freopen(file.c_str(), "w", stdout);
//write to the file
cout << data << endl;
return EXIT_SUCCESS;
}
</code>
</pre>
</li>
<li>
<h4>Removing file:</h4>
After all these long programs, removing a file will feel like the easiest task out there (As I stated earlier, it is almost always easier to destroy something, right?).
<pre>
<code id="program" class="language-c++">
#include <filesystem>
#include <iostream>
#include <cstdio>
#include <string>
namespace fs = std::filesystem;
using namespace std;
int main()
{
string filepath;
cin >> filepath;
//Works irrespective of the argument being a string or a filepath
fs::remove(filepath);
return EXIT_SUCCESS;
}
</code>
</pre>
</li>
</ol>
</p>
<p>
So, these were the functions that I found to be the most useful for general purpose. I will obviously keep updating this with new functions and information but feel free to give feedbacks regarding the need for any improvements, clarifications, rectifications or addition of some information.
</p>
<h2>References:</h2>
<ul>
<li><a href="https://en.cppreference.com/w/cpp/filesystem">Filesystem Library - Cppreference</a></li>
<li><a href="https://carlosvin.github.io/posts/recursive-directory-iterator/en/">Filesystem in C++17 - Carlos</a></li>
<li><a href="https://docs.microsoft.com/en-us/cpp/standard-library/filesystem?view=vs-2019">Filesystem - Microsoft docs</a></li>
<li><a href="https://www.codingame.com/playgrounds/5659/c17-filesystem">C++17 Filesystem - Codingame</a></li>
</ul>
</section>
<!--footer-->
<footer>
<small>© All rights reserved.</small>
</footer>
</body>
</html>