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

一 文件

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

1#include <iostream> 2#include <fstream> 3using namespace std; 4 5int main() 6{ 7 char szData[200] = "123456 test"; 8 fstream fFile; 9 fFile.open("test.txt", ios::app | ios::out | ios::in); 10 /****************将数据写入文件-begin***************/ 11 fFile << szData; 12 /****************将数据写入文件-end***************/ 13 14 /*************** 将数据从文件中读取出来-begin******************/ 15 fFile.seekg(0, ios::end); 16 int iSize = fFile.tellg(); //计算出文件大小 17 fFile.seekg(ios::beg); //从文件最前面开始读取 18 fFile >> noskipws; //设置读取空格、回车 19 std::string strDataOut; 20 for (int i = 0; i < iSize/*!afile.eof()*/; i++) 21 { 22 char c; 23 fFile >> c; 24 strDataOut.push_back(c); 25 } 26 27 cout << strDataOut.c_str(); 28 /*************** 将数据从文件中读取出来-end******************/ 29 fFile.close(); 30 return 0; 31}

1.2 使用windows API读写文件

1#include <windows.h> 2#include <string> 3 4int main() 5{ 6 std::string strFileName = "test.txt"; 7 /*************************写文件-begin******************************/ 8 std::string strData = "123456 test"; 9 DWORD dwReturn; 10 HANDLE hFileWrite = CreateFileA(strFileName.c_str(), GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); 11 if (INVALID_HANDLE_VALUE != hFileWrite) 12 { 13 WriteFile(hFileWrite, strData.c_str(), strData.length(), &dwReturn, NULL); 14 CloseHandle(hFileWrite); 15 } 16 /*************************写文件-end******************************/ 17 18 /*************************读文件-begin******************************/ 19 DWORD bytesRead = 0; 20 char szBuffer[1024] = { 0 }; 21 HANDLE hFileRead = CreateFileA(strFileName.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); 22 if (INVALID_HANDLE_VALUE != hFileRead) 23 { 24 ReadFile(hFileRead, szBuffer, 1024/*static_cast<DWORD>(length)*/, &bytesRead, NULL); 25 CloseHandle(hFileRead); 26 } 27 /*************************读文件-end******************************/ 28 29 return 0; 30}

1.3 linux读写文件

1#include <fcntl.h> 2#include <unistd.h> 3#include <string> 4#include <iostream> 5 6int main() 7{ 8 std::string strPath = "test.txt"; 9 /*************************写文件-begin******************************/ 10 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); 11 if ( -1 == iFileWrite) 12 { 13 return 0; 14 } 15 std::string strBuffer = "Test Data"; 16 int n = write(iFileWrite, strBuffer.c_str(), strBuffer.length()); 17 ::close(iFileWrite); 18 /*************************写文件-end******************************/ 19 20 /*************************读文件-begin******************************/ 21 char szBuffer[1024] = { 0 }; 22 int iFileRead = ::open(strPath.c_str(), O_RDONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); 23 if (-1 == iFileRead) 24 { 25 return 0; 26 } 27 read(iFileRead, szBuffer, 1024); 28 std::cout << szBuffer; 29 ::close(iFileRead); 30 /*************************读文件-end******************************/ 31 return 0; 32}

二 文件夹

1.1 Windows

1. 创建文件夹

1#include <direct.h> 2#include <iostream> 3#include <io.h> 4 5using namespace std; 6 7int main() 8{ 9 string folderPath = "E:\\Test\\Dir"; 10 if (0 != access(folderPath.c_str(), 0)) 11 { 12 int iRst = mkdir(folderPath.c_str()); // 需要迭代创建,即创建子文件夹时父文件夹必须存在 13 } 14 15 return 0; 16}

2. 遍历文件夹

1#include "stdafx.h" 2#include <io.h> 3#include <string> 4#include <vector> 5#include <iostream> 6#include <windows.h> 7#include <atlstr.h> 8using namespace std; 9 10//获取文件夹下所有文件名及文件夹总大小 11DWORD TraversalFolder(string strPath, vector<string>& files) 12{ 13 DWORD dwRtn = 0; 14 long hFolder = 0; //文件句柄 15 struct _finddata_t fileinfo; //文件信息 16 string strFileName = ""; 17 18 if ((hFolder = _findfirst(strFileName.assign(strPath).append("\\*").c_str(), &fileinfo)) != -1) 19 { 20 do 21 { 22 DWORD dwSize = 0; 23 //如果是目录,迭代之;如果不是,加入列表 24 if ((fileinfo.attrib & _A_SUBDIR)) 25 { 26 if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0) 27 { 28 dwSize = TraversalFolder(strFileName.assign(strPath).append("\\").append(fileinfo.name), files); 29 } 30 } 31 else 32 { 33 files.push_back(strFileName.assign(strPath).append("\\").append(fileinfo.name)); 34 dwSize = fileinfo.size; 35 } 36 dwRtn += dwSize; 37 } while (0 == _findnext(hFolder, &fileinfo)); 38 39 _findclose(hFolder); 40 } 41 return dwRtn; 42} 43 44int main() 45{ 46 char * filePath = "E:/test"; 47 DWORD dwFolderSize; 48 vector<string> files; 49 dwFolderSize = TraversalFolder(filePath, files);//获取文件夹下所有文件名及文件夹总大小 50 system("pause"); 51}

1.2 Linux

1. 创建文件夹

1#include <sys/stat.h> 2#include <iostream> 3#include <string> 4 5int main() 6{ 7 std::string strParh = "Test111"; 8 int isCreate = ::mkdir(strParh.c_str(), S_IRUSR | S_IWUSR | S_IXUSR | S_IRWXG | S_IRWXO);// // 需要迭代创建,即创建子文件夹时父文件夹必须存在 9 if (0 == isCreate) 10 { 11 std::cout << "mkdir succeeded"; 12 } 13 else 14 { 15 std::cout << "mkdir failed"; 16 } 17 18 return 0; 19}

2. 遍历文件夹

1#include<stdio.h> 2#include<stdlib.h> 3#include<unistd.h> 4#include<sys/stat.h> 5#include<string.h> 6#include<fcntl.h> 7#include<dirent.h> 8 9void TraversalFolder(const char *filedir) 10{ 11 struct stat dirstat; 12 if (stat(filedir, &dirstat) == -1) 13 { 14 printf("cant access to %s", filedir); 15 exit(1); 16 } 17 18 if (dirstat.st_mode & S_IFDIR) 19 { 20 struct dirent *entry; 21 DIR * dir; 22 dir = opendir(filedir); 23 printf("%s\n", filedir); 24 while ((entry = readdir(dir)) != NULL) 25 { 26 if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))continue; 27 char src[255]; 28 strcpy(src, filedir); 29 strcat(src, "/"); 30 chdir(strcat(src, entry->d_name)); 31 TraversalFolder(src); 32 chdir(filedir); 33 } 34 } 35 else 36 { 37 printf("--%s\n", filedir); 38 } 39 40} 41int main(int argc, char *args[]) 42{ 43 if (argc != 2) 44 { 45 printf("param error"); 46 } 47 TraversalFolder(args[1]); 48 return 0; 49}
点赞
收藏

评论区

加载中...

相关推荐

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

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

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

C# Aspose.Cells导出xlsx格式Excel,打开文件报“Excel 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃”

报错信息:最近打开下载的Excel,会报如下错误。(xls格式不受影响)!(https://oscimg.oschina.net/oscnet/2b6f0c8d7f97368d095d9f0c96bcb36d410.png)!(https://oscimg.oschina.net/oscnet/fe1a8000d00cec3c

Linux查看GPU信息和使用情况

1、Linux查看显卡信息:lspci|grepivga2、使用nvidiaGPU可以:lspci|grepinvidia!(https://oscimg.oschina.net/oscnet/36e7c7382fa9fe49068e7e5f8825bc67a17.png)前边的序号"00:0f.0"是显卡的代