windows中C++文件或文件夹操作(修改)

windows中C++文件或文件夹操作

C++ 文件读写操作,可参见 https://blog.csdn.net/cnds123/article/details/109685986

C++中判断文件或文件夹是否存在

可以使用_access()函数来判断文件或文件夹是否存在。这个函数定义在头文件io.h中,原型如下:

int _access(const char* path, int mode);

其中,path参数是要检查的文件或文件夹的路径,mode参数指定了检查的类型,可以是以下值之一:

0:检查文件或文件夹是否存在。

2:检查写权限(即文件或文件夹是否可写)。

4:检查读权限(即文件或文件夹是否可读)。

返回值为0表示检查成功,表明文件或文件夹存在或有对应的权限;否则返回-1表示检查失败,表明文件或文件夹不存在或无对应的权限。

C++判断文件或文件夹是否存在,源码如下:

//判断文件或文件夹是否存在 
#include <iostream>
#include <io.h>
using namespace std;

int main() {
    const char* path = "d:/CreateFolder";
    if (_access(path, 0) == 0) {
        cout<< path << ":存在" << endl;
    } else {
        cout<< path << "不存在" << endl;
    }

    return 0;
}

C++ 创建文件夹

Windows操作系统中,利用C/C++的函数system() 函数可以调用 dos 命令,本示例是在 d:\ 路径下创建一个叫做 testFolder 的文件夹。

C++ 创建文件夹的源码如下:

#include <iostream>
using namespace std;

int main()
{
    string folderPath = "d:\\testFolder"; 

    string path;
    path = "mkdir " + folderPath;  
    system(path.c_str());

    return 0;
}

C++ 删除文件夹,源码如下:

#include <iostream>
using namespace std;

int main()
{
    string folderPath = "d:\\testFolder"; 

    string path;
    path = "rmdir " + folderPath;  
    system(path.c_str());

    return 0;
}

C++ 文件改名,源码如下:

#include <iostream>
using namespace std;
 
int main()
{
    string oldName = "d:\\test.png"; 
 	string newName = "d:\\testNew.png"; 

	if (!rename(oldName.c_str(), newName.c_str()))
	{
		cout << "rename success "<< endl;
	}
	else
	{
		cout << "rename error "<< endl;
	}
 
	return 0;
}

windows中c++ 遍历某个目录下所有文件

#include <iostream>
#include <io.h>
#include <string>
using namespace std;
 
 
void dir(string path)
{
    long hFile = 0;
    struct _finddata_t fileInfo;
    string pathName, exdName;
 
 
    if ((hFile = _findfirst(pathName.assign(path).
        append("\\*").c_str(), &fileInfo)) == -1) {
        return;
    }
    do {
        if (fileInfo.attrib&_A_SUBDIR) {
            string fname = string(fileInfo.name);
            if (fname != ".." && fname != ".") {
                dir(path + "\\" + fname);
            } 
        } else {
            cout << path << "\\" << fileInfo.name << endl;
        }
    } while (_findnext(hFile, &fileInfo) == 0);
    _findclose(hFile);
    return;
}
 
 
int main()
{
    string path="d:\\testA";  //在这里指定遍历文件夹 
    dir(path);
    return 0;
}

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学习&实践爱好者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值