【IT168 技术文章】
一、实例
在《CPPUNIT基本原理》中举了一个简单的例子,在这个实例的基础上,另外写了一个稍微复杂的例子用作 cppunit的测试
这个实例包含一个Write2File cpp,一个Write2File h文件,功能是实现从一个文件复制内容到另一个文件。具体实现如下:
Write2File.cpp的代码:
#include "Write2File.h"
Write2File::Write2File()
{
}
Write2File::~Write2File()
{
}
int Write2File::Process() //主过程
{
ReadCfgFile( );
if( ReadFileSrc() )
{
return -1;
}
if( WriteFileOut() )
{
return -1;
}
return 0;
}
int Write2File::ReadCfgFile() //这个函数本来是想实现从配置文件中获取输出目录和输出目录的,后来简化了这段代码,直接将路径赋值给变量了。
{
strcpy( SrcPath , m_srcp );
strcpy( OutPath , m_outp );
return 0;
}
int Write2File::ReadFileSrc() //读取源文件的内容
{
FILE *fp = NULL;
memset( SrcFilename , 0 ,sizeof( SrcFilename ) );
sprintf( SrcFilename , "%s/test_src.txt" , SrcPath );
if( ( fp = fopen( SrcFilename , "r" ) ) == NULL )
{
printf( "Open srcfile error :%s\n" , SrcFilename );
return -1;
}
fnum = stat(SrcFilename,&statbuf);
if( fnum < 0 )
{
printf("there need size of file\n");
}
fnum = statbuf.st_size; //源文件的大小
fread( m_Buf , statbuf.st_size, 1 , fp );
fclose( fp );
return 0;
}
int Write2File::WriteFileOut() //将读取的内容输入到输出文件
{
FILE *fp = NULL;
memset( OutFilename , 0 , sizeof(OutFilename ) );
sprintf( OutFilename , "%s/test_out.txt", OutPath );
if( access(OutFilename , F_OK) == 0 ) unlink( OutFilename );
if( ( fp = fopen(OutFilename , "a+") ) == NULL )
{
printf("Read file %s error!\n",OutFilename );
return -1;
}
fwrite( m_Buf , statbuf.st_size , 1 , fp );
fclose( fp );
return 0;
}
int main(int argc , const char **argv)
{
Write2File writefile;
if( argc!=3 )
{
printf( "ERROR,Example: Write2File srcpath outpath \n" );
return -1;
}
m_argc = argc;
strcpy( m_srcp , argv[1] );
strcpy( m_outp , argv[2] );
//m_srcp = argv;
writefile.Process();
return 0;
}
Write2File.h的代码:
#include <stdlib.h>
#include <math.h>
#include <iostream.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sstream>
class Write2File
{
public:
Write2File();
~Write2File();
public:
char m_Buf[m_BufSize];
//protected:
int ReadCfgFile();
int Process();
int ReadFileSrc();
int WriteFileOut();
char SrcPath[256];
char OutPath[256];
char SrcFilename[256];
char OutFilename[256];
char Logfile[256];
char Logfilepath[256];
char Logfilename[256];
struct stat statbuf;
int fnum;
};
int m_argc;
char m_srcp[256];
char m_outp[256];