以下コードです
//template.h
#ifndef INCLUDE_TEMPLATE
#define INCLUDE_TEMPLATE
template <typename T>
T numof(T* hoge)
{
return sizeof(hoge)/sizeof(hoge[0]);
}
#endif
//file.h
#ifndef INCLUDE_FILE
#define INCLUDE_FILE
#include <stdio.h>
class Cfile
{
private:
FILE *fp;
char output[256];
char input[256];
bool copy;
bool modefyflags(const char* psSource,char* psDest,int nsize);
public:
Cfile();
Cfile(const Cfile& rother);
~Cfile();
bool Open(const char* ps_file,const char* pz_flag);
void Close();
void Read();
void Write();
inline bool Cfile::Valid() const //fpが有効か
{
return fp != NULL;
}
};
#endif
//file.cpp
#include<stdio.h>
#include<string.h>
#include"file.h"
#include"template.h"
Cfile::Cfile()
{
memset(input,(int)'\0',sizeof(input));
memset(output,(int)'\0',sizeof(output));
fp = NULL;
copy = false;
}
Cfile::Cfile(const Cfile& rother)
{
fp = rother.fp;
copy = true;
}
Cfile::~Cfile()
{
if(copy == false)
Close();
}
bool Cfile::Open(const char* ps_file,const char* ps_flag)
{
Close();
char buf_flag[8];
if(modefyflags(ps_flag,buf_flag,numof(buf_flag)) == false)
return false;
fp = fopen(ps_file,ps_flag);
return (fp != NULL);
}
void Cfile::Close()
{
if(Valid() == true)
{
fclose(fp);
}
}
bool Cfile::modefyflags(const char* psSource,char* psDest,int nsize)
{
bool binary;
binary = (strchr(psSource,'b') != NULL); //フラグpsSoruceがバイナリ指定ならbinaryにtrueを代入
if((int)strlen(psSource) > nsize - 1 - !binary)
return false;
strcpy(psDest,psSource);
if(binary == false)
strcat(psDest,"b");
return true;
}
void Cfile::Read()
{
if(Valid() == false)
{
printf("ファイルを開いてから行ってください");
return;
}
fread(output,1,256,fp);
printf("%s\n",output);
}
void Cfile::Write()
{
if(Valid() == false)
{
printf("ファイルを開いてから行ってください");
return;
}
int size = 0;
printf("書き込む文字を入力");
scanf("%s",input);
int i;
for(i=0;input[i]!='\0';i++)
{
size++;
}
fwrite(input,1,(size_t)size,fp);
}
//main.cpp
#include<stdio.h>
#include"file.h"
int main()
{
Cfile file;
char name[32];
int mode;
printf("開きたいファイルを選択\n");
scanf("%s",name);
printf("何をなさいますか?\n1,書き込み\n2,読み込み\n");
scanf("%d",&mode);
if(mode == 1)
{
file.Open(name,"wb");
file.Write();
}
else if(mode == 2)
{
file.Open(name,"rb");
file.Read();
}
else
printf("1か2でお願いします\n");
return 0;
}