C++小技巧日常记录

1.连接两个字符串

char a[20] = "hello ";
char b[20] = "world"
strcat(a, b);
cout << a << endl;

//hello world

2. 判断文件/文件夹是否存在

// windows

//mode的值和含义如下所示:
//00——只检查文件是否存在
//02——写权限
//04——读权限
//06——读写权限

#include <io.h>

// 文件夹只能检查是否存在
// 若文件不存在,返回-1,否则,返回0
int result = _access(filepath, mode);

3.获取目录下所有文件

#include <Windows.h>
#include <cstring>
#include <vector>
#include <io.h>

// 获取所有后缀名为avi的文件,存到files向量中
void get_all_files(string path, vector<string>& files) {
    long file_handle = 0;
    struct _finddata_t fileinfo;
    string p;
    if ((file_handle = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1) {
        do {
            if ((fileinfo.attrib & _A_SUBDIR)) {
                if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0) {
                    if (string(fileinfo.name).find(".avi") != string::npos) {
                        files.push_back(p.assign(path).append("\\").append(fileinfo.name));
                    }
                    get_all_files(p.assign(path).append("\\").append(fileinfo.name), files);
                }
            }
            else if (string(fileinfo.name).find(".avi") != string::npos){
                files.push_back(p.assign(path).append("\\").append(fileinfo.name));
            }
        } while (_findnext(file_handle, &fileinfo) == 0);
        _findclose(file_handle);
    }
}

4. 使用fstream类打开文件

    /*------------------------------------------*\
    | ios::in   为输入(读)而打开文件                
    | ios::out  为输出(写)而打开文件                
    | ios::ate  初始位置:文件尾                    
    | ios::app  所有输出附加在文件末尾              
    | ios::trunc    如果文件已存在则先删除该文件     
    | ios::binary   二进制方式                    
    \*-----------------------------------------*/
    fstream outfile;
    outfile.open("result.txt", ios::app);
    outfile.close();

5.调用windows的Api查看文件(夹)大小

// 功能:检查D盘是否连接,查看剩余空间
bool checkHardwared() {
    // check if file can be opened
    SYSTEM_POWER_STATUS lpPwrStatus;
    GetSystemPowerStatus(&lpPwrStatus);

    unsigned _int64 freeBytesToCaller, totalBytes, freeBytes;
    bool isDiskConnected = GetDiskFreeSpaceEx("D:\\", (PULARGE_INTEGER)&freeBytesToCaller, (PULARGE_INTEGER)&totalBytes, (PULARGE_INTEGER)&freeBytes);
    if (!isDiskConnected) {
        cout << "硬盘末连接" << endl;
        Sleep(1000);
        return false;
    }
    else if ((float)freeBytesToCaller / 1024 / 1024 < 2048) {
        cout << "空间不足" << endl;
        Sleep(1000);
        return false;
    }
    else {
        system("md D:\\Data");
    }
    return true;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值