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

一 文件

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

评论

暂无评论