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;
}