Site icon Learn C++

This Is How To Use File Operations In C++

C++ is a great programming language that you can reach every part of your device or operating system. File system of an operating system is very important and you must know well both File System features of that Operating System and features of your programming language. Thus, we can copy, delete and get file information.

In this post, you’ll learn how to use DOS commands to operate on files, as well as how to use system commands in C++ to list, copy, rename, delete, and move files and set file permissions using system commands in C++. By learning how to use file operations in c++, it will help you to easily build C++ applications using the C++ App.

Using System Commands

On Windows and some other operating systems you can use System() command to use System Commands like cd, mkdir rmdir commands etc. For example we can create a folder by using mkdir command and we can copy folder to another folder by using xcopy command and we can remove a folder by using rmdir command. See example below,

[crayon-673fdbf8da69b366955362/]

How to list files in a directory or folder in C++

In C++, Std library has great features, classes and methods, and there is a directory_iterator(), we can use this to get all file names in that path.

[crayon-673fdbf8da6a2073588910/]

We can use this directory_iterator() with for() loop as in given example below,

[crayon-673fdbf8da6a4760570895/]

We can use recursive_directory_iterator() to list all files in that folder.

How to check if a file exists with C++

We can use filesystem::exists(path+filename) to check a file if it exists in a file system.

[crayon-673fdbf8da6a5038120258/]

How to copy a file in C++

[crayon-673fdbf8da6a6389431384/]

How do I set or change file permissions with C++?

[crayon-673fdbf8da6a7220730835/]

Creating a file with specific permissions

[crayon-673fdbf8da6a8784053356/]

How to rename a file in C++

[crayon-673fdbf8da6a9256188695/]

How to remove or delete a file with C++

[crayon-673fdbf8da6aa289861940/]

You can download and try RAD Studio C++ Builder for free. Why not try it today?

Exit mobile version