C++文件及文件夹操作整理(代码示例)

Wesley13
• 阅读 654

一 文件

1.1 使用C++标准库中的IO库(fstream)读写文件

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    char szData[200] = "123456 test";
    fstream fFile;
    fFile.open("test.txt", ios::app | ios::out | ios::in);
    /****************将数据写入文件-begin***************/
    fFile << szData;
    /****************将数据写入文件-end***************/

    /*************** 将数据从文件中读取出来-begin******************/
    fFile.seekg(0, ios::end);
    int iSize = fFile.tellg(); //计算出文件大小
    fFile.seekg(ios::beg); //从文件最前面开始读取
    fFile >> noskipws; //设置读取空格、回车
    std::string strDataOut;
    for (int i = 0; i < iSize/*!afile.eof()*/; i++)
    {
        char c;
        fFile >> c;
        strDataOut.push_back(c);
    }

    cout << strDataOut.c_str();
    /*************** 将数据从文件中读取出来-end******************/
    fFile.close();
    return 0;
}

1.2 使用windows API读写文件

#include <windows.h>
#include <string>

int main()
{
    std::string strFileName = "test.txt";
    /*************************写文件-begin******************************/
    std::string strData = "123456 test";
    DWORD dwReturn;
    HANDLE hFileWrite = CreateFileA(strFileName.c_str(), GENERIC_WRITE,  FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (INVALID_HANDLE_VALUE != hFileWrite)
    {
        WriteFile(hFileWrite, strData.c_str(), strData.length(), &dwReturn, NULL);
        CloseHandle(hFileWrite);
    }
    /*************************写文件-end******************************/

    /*************************读文件-begin******************************/
    DWORD bytesRead = 0;
    char szBuffer[1024] = { 0 };
    HANDLE hFileRead = CreateFileA(strFileName.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (INVALID_HANDLE_VALUE != hFileRead)
    {
        ReadFile(hFileRead, szBuffer, 1024/*static_cast<DWORD>(length)*/, &bytesRead, NULL);
        CloseHandle(hFileRead);
    }
    /*************************读文件-end******************************/
    
    return 0;
}

1.3 linux读写文件

#include <fcntl.h>
#include <unistd.h>
#include <string>
#include <iostream>

int main()
{
    std::string strPath = "test.txt";
    /*************************写文件-begin******************************/
    int iFileWrite = ::open(strPath.c_str(), O_TRUNC | O_APPEND | O_CREAT | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
    if ( -1 == iFileWrite)
    {
        return 0;
    }
    std::string strBuffer = "Test Data";
    int n = write(iFileWrite, strBuffer.c_str(), strBuffer.length());
    ::close(iFileWrite);
    /*************************写文件-end******************************/

    /*************************读文件-begin******************************/
    char szBuffer[1024] = { 0 };
    int iFileRead = ::open(strPath.c_str(), O_RDONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
    if (-1 == iFileRead)
    {
        return 0;
    }
    read(iFileRead, szBuffer, 1024);
    std::cout << szBuffer;
    ::close(iFileRead);
    /*************************读文件-end******************************/
    return 0;
}

二 文件夹

1.1 Windows

1. 创建文件夹

#include <direct.h>
#include <iostream>
#include <io.h>

using namespace std;

int main()
{
    string folderPath = "E:\\Test\\Dir";
    if (0 != access(folderPath.c_str(), 0))
    {
        int iRst = mkdir(folderPath.c_str());   // 需要迭代创建,即创建子文件夹时父文件夹必须存在
    }

    return 0;
}

2. 遍历文件夹

#include "stdafx.h"
#include <io.h>
#include <string>
#include <vector>
#include <iostream>
#include <windows.h>
#include <atlstr.h>
using namespace std;

//获取文件夹下所有文件名及文件夹总大小
DWORD TraversalFolder(string strPath, vector<string>& files)
{
    DWORD dwRtn = 0;
    long hFolder = 0;                                     //文件句柄
    struct _finddata_t fileinfo;                         //文件信息
    string strFileName = "";

    if ((hFolder = _findfirst(strFileName.assign(strPath).append("\\*").c_str(), &fileinfo)) != -1)
    {
        do
        {
            DWORD dwSize = 0;
            //如果是目录,迭代之;如果不是,加入列表
            if ((fileinfo.attrib &  _A_SUBDIR))
            {
                if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
                {
                    dwSize = TraversalFolder(strFileName.assign(strPath).append("\\").append(fileinfo.name), files);
                }
            }
            else
            {
                files.push_back(strFileName.assign(strPath).append("\\").append(fileinfo.name));
                dwSize = fileinfo.size;
            }
            dwRtn += dwSize;
        } while (0 == _findnext(hFolder, &fileinfo));

        _findclose(hFolder);
    }
    return dwRtn;
}

int main()
{
    char * filePath = "E:/test";
    DWORD dwFolderSize;
    vector<string> files;
    dwFolderSize = TraversalFolder(filePath, files);//获取文件夹下所有文件名及文件夹总大小
    system("pause");
}

1.2 Linux

1. 创建文件夹

#include <sys/stat.h>
#include <iostream>
#include <string>

int main()
{
    std::string strParh = "Test111";
    int isCreate = ::mkdir(strParh.c_str(), S_IRUSR | S_IWUSR | S_IXUSR | S_IRWXG | S_IRWXO);// // 需要迭代创建,即创建子文件夹时父文件夹必须存在
    if (0 == isCreate)
    {
        std::cout << "mkdir succeeded";
    }
    else
    {
        std::cout << "mkdir failed";
    }

    return 0;
}

2. 遍历文件夹

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/stat.h>
#include<string.h>
#include<fcntl.h>
#include<dirent.h>

void TraversalFolder(const char *filedir)
{
    struct stat dirstat;
    if (stat(filedir, &dirstat) == -1)
    {
        printf("cant access to %s", filedir);
        exit(1);
    }

    if (dirstat.st_mode & S_IFDIR)
    {
        struct dirent *entry;
        DIR * dir;
        dir = opendir(filedir);
        printf("%s\n", filedir);
        while ((entry = readdir(dir)) != NULL)
        {
            if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))continue;
            char src[255];
            strcpy(src, filedir);
            strcat(src, "/");
            chdir(strcat(src, entry->d_name));
            TraversalFolder(src);
            chdir(filedir);
        }
    }
    else
    {
        printf("--%s\n", filedir);
    }

}
int main(int argc, char *args[])
{
    if (argc != 2)
    {
        printf("param error");
    }
    TraversalFolder(args[1]);
    return 0;
}
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Stella981 Stella981
2年前
Opencv中Mat矩阵相乘——点乘、dot、mul运算详解
Opencv中Mat矩阵相乘——点乘、dot、mul运算详解2016年09月02日00:00:36 \牧野(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fme.csdn.net%2Fdcrmg) 阅读数:59593
Stella981 Stella981
2年前
C# Aspose.Cells导出xlsx格式Excel,打开文件报“Excel 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃”
报错信息:最近打开下载的Excel,会报如下错误。(xls格式不受影响)!(https://oscimg.oschina.net/oscnet/2b6f0c8d7f97368d095d9f0c96bcb36d410.png)!(https://oscimg.oschina.net/oscnet/fe1a8000d00cec3c
Stella981 Stella981
2年前
Linux查看GPU信息和使用情况
1、Linux查看显卡信息:lspci|grepivga2、使用nvidiaGPU可以:lspci|grepinvidia!(https://oscimg.oschina.net/oscnet/36e7c7382fa9fe49068e7e5f8825bc67a17.png)前边的序号"00:0f.0"是显卡的代
Wesley13 Wesley13
2年前
FLV文件格式
1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.  
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Stella981 Stella981
2年前
Github标星5300+,专门为程序员开发文档开源管理系统,我粉了
!(https://oscimg.oschina.net/oscnet/a11909a041dac65b1a36b2ae8b9bcc5c432.jpg)码农那点事儿关注我们,一起学习进步!(https://oscimg.oschina.net/oscnet/f4cce1b7389cb00baaab228e455da78d0
Stella981 Stella981
2年前
Nginx反向代理upstream模块介绍
!(https://oscimg.oschina.net/oscnet/1e67c46e359a4d6c8f36b590a372961f.gif)!(https://oscimg.oschina.net/oscnet/819eda5e7de54c23b54b04cfc00d3206.jpg)1.Nginx反