跳至主要內容

FileUtils

chanchaw大约 2 分钟cpp

读写文本文件

下面的方法读取到中文字符输出到控制台后会显示为乱码

#include <fstream>
using namespace std;

// 读取文本文件
void ReadTxt() {
	ifstream fin("temp.txt");
	char buf[1024] = {0};

	// 循环读取,每次读取一行	
	while (fin.getline(buf, sizeof(buf))) {
		cout << buf << endl;
	}
	
	fin.close();
}

// 写入文本文件
void WriteTxt() {
	fstream f;
	//追加写入,在原来基础上加了ios::app 
	f.open("test.txt", ios::out | ios::app);
	// 每写入一行内容后换行
	f << "第一行的内容" << endl;
	f << "第2行的内容" << endl;
	f << "第3333行的内容" << endl;
	f.close();
}

修改文件名

#include <fstream>
using namespace std;

/*
	修改文件名,调用方法:

	std::fstream f;
	std::string oldFileName = "031 第31集 警幻仙子暗提点.mp3";
	std::string newFileName = "第31集 警幻仙子暗提点.mp3";

	try {
		renameFile(oldFileName, newFileName);
		std::cout << "修改二进制文件名成功" << std::endl;
	}
	catch (const std::exception& e) {
		std::cerr << "Error: " << e.what() << std::endl;
	}
*/
void renameFile(const std::string& oldName, const std::string& newName) {
	std::ifstream oldFile(oldName, std::ios::binary); // Open the old file in binary mode
	if (!oldFile.is_open()) {
		throw std::runtime_error("Failed to open the old file.");
	}

	std::ofstream newFile(newName, std::ios::binary); // Open the new file in binary mode
	if (!newFile.is_open()) {
		throw std::runtime_error("Failed to create the new file.");
	}

	char c;
	while (oldFile.get(c)) {
		newFile.put(c);
	}

	oldFile.close();
	newFile.close();

	if (remove(oldName.c_str()) != 0) {
		throw std::runtime_error("Failed to remove the old file.");
	}
}

遍历目录下的所有文件

/*
@author:CodingMengmeng
@theme:获取指定文件夹下的所有文件名
@time:2017-1-13 11:46:22
@blog:
*/
#include <io.h>
#include <iostream>
#include <vector>
using namespace std;

void getFiles(string path, vector<string>& files)
{
	//文件句柄
	intptr_t hFile = 0;
	//文件信息,声明一个存储文件信息的结构体
	struct _finddata_t fileinfo;
	string p;//字符串,存放路径
	if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)//若查找成功,则进入
	{
		do
		{
			//如果是目录,迭代之(即文件夹内还有文件夹)
			if ((fileinfo.attrib &  _A_SUBDIR))
			{
				//文件名不等于"."&&文件名不等于".."
				//.表示当前目录
				//..表示当前目录的父目录
				//判断时,两者都要忽略,不然就无限递归跳不出去了!
				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
					getFiles(p.assign(path).append("\\").append(fileinfo.name), files);
			}
			//如果不是,加入列表
			else
			{
				// files.push_back(p.assign(path).append("\\").append(fileinfo.name));
				files.push_back(fileinfo.name);
			}
		} while (_findnext(hFile, &fileinfo) == 0);
		//_findclose函数结束查找
		_findclose(hFile);
	}
}


int main() {
	// 可以如下设置绝对路径,也可以设置相对路径:./
	const char* filePath = "D:\\logs\\";
	vector<string> files;

	// 获取该路径下的所有文件
	getFiles(filePath, files);

	int size = files.size();
	for (int i = 0; i < size; i++)
	{
		cout << files[i].c_str() << endl;
	}
	system("pause");
}