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-6629fafc26c66634281098/]

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-6629fafc26c6f581383086/]

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

[crayon-6629fafc26c71394795268/]

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-6629fafc26c72957039207/]

How to copy a file in C++

[crayon-6629fafc26c7a828898464/]

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

[crayon-6629fafc26c7c590336222/]

Creating a file with specific permissions

[crayon-6629fafc26c7e892183213/]

How to rename a file in C++

[crayon-6629fafc26c80761070517/]

How to remove or delete a file with C++

[crayon-6629fafc26c84745193315/]

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

Exit mobile version