【#文档大全网# 导语】以下是®文档大全网的小编为您整理的《计算机等级考试C++基础——C++文件拷贝代码》,欢迎阅读!
计算机等级考试C++基础——C++文件拷贝代码
用C++些文件拷贝程序远远比想象的要困难的多,和C#仅使用的File类和Directory类相比,直接操作windows api更加有趣。这个过程让我体会到的不仅仅是api,更多是编写程序这一个过程的本质。
先和大家分享一下我的代码,还请各位C++前辈们指教。 .h文件
#pragma once #include
#include "file.h" using namespace std; namespace Common {
namespace File {
class SyncFolder : public Common::File::FileClass {
private:
wstring m_sourceDirectory; wstring m_targetDirectory; const wstring * m_ext; const bool * m_reverseExt; protected:
void FileMethod(const wstring&); public:
SyncFolder(const wstring &sourceDirectory, const wstring &targetDirectory,const wstring &ext, bool reverseExt):FileClass(),
m_sourceDirectory(Common::File::GetSecurePath(sourceDirectory)),m_targetDirectory(Common::File::GetSecurePath(targetDirectory)) {
m_ext = new wstring(ext);
m_reverseExt = new bool(reverseExt); }
~SyncFolder(void) {
delete m_ext;
delete m_reverseExt; }
void Exec(); };
} }
.cpp文件
#include "StdAfx.h" #include "SyncFolder.h" #include "File.h"
void Common::File::SyncFolder::Exec() {
ReadFiles(m_sourceDirectory, *m_ext); }
void Common::File::SyncFolder::FileMethod(const wstring& fileName) {
//获取相对路径 wstring offsetPath =
Common::File::GetRelativePath(m_sourceDirectory, Common::File::GetPathFromFilePath(fileName)); //获取新路径
wstring targetFilePath; if(offsetPath.empty())
targetFilePath = m_targetDirectory; else
targetFilePath = m_targetDirectory + L"" + offsetPath; //创建文件夹
Common::File::CreatePath(targetFilePath); //创建新文件路径 wstring newFileName = targetFilePath + L"" + Common::File::GetFileNameFromFilePath(fileName); //复制文件
CopyFile(fileName.c_str(), newFileName.c_str(), true); }
其实在之前的一篇blog中,我写了一个遍历文件目录的函数( 文件夹遍历代码C++(win32平台)),在这个函数的参数列表中,考试,大提示有一个函数指针。考试,大意图是通过这个函数指针,能够处理遍历到的文件。由于在C#中,可以通过delegate来声明一个类似与函数指针的类型,然后通过该类型来定义一个对象来指向执行方法的地址,所以我也想在C++中如法炮制。可是最后C++编译器告诉我,这种写法是错误的。在C++中,函数指针指向的是一个静态地址,如果我要将指针指向类实例的一个成员方法,这在C++中是不允许的(听说boost中一个解决方法)。这让我明白了C++和C#中相似的地方并不相同。不过这也给了我想象的空间:去想象C#编译器是如何用delegate去实现函数指针的功能的或者说它们之间有本质的区别。
另外一个很重要的体验是,C++的开发环境远没有C#那么智能(VS2008),特别是智能感知那一块。这让我在最开始些代码的时候总是感到不稳,像一个醉汉走路,摇摇晃晃的。后来我发现,这种担心源于我自己对C++编译器的类型检查特性没有充分的认识。我们可以放心大胆的去写代码,然后compile,如果有问题,编译器会很精确的告诉你。这种认识对重构代码很有帮助。在之后的工作中,对于那些C#代码,我都感很放心的去重构,因为编
译器会告诉我问题出在什么地方。也就是基于这种认识,在写C#代码的时候,尽量避免使用像datatable之类的类型,因为编译器不能对其中的数据类型进行类型检查,这样我们也就享受不到编译器类型检查这项功能带来的实惠。 还有就是单元测试的工作方式。最开始写C++代码,每写一行代码我都不敢确定它的输出结果是正确的或是什么样子。为了解决这个问题,我基本上为每个函数编写专门的调试代码。后来我发现这是一种不错的工作方式,效率很高。这种工作方式就是在.net世界中的单元测试。
本文来源:https://www.wddqxz.cn/facef20fac45b307e87101f69e3143323968f584.html