接口的封装
将写文件操作封装到一个接口中:w_file()
#include "stdio.h"
#include "./file_IO.h"
// 写文件操作
int w_printf(FILE *fp, char *dat, int dat_num)
{
unsigned int i, j;
if(!fp)
{
printf("Fopen file error!\n");
return -1;
}
if(!dat || dat_num == 0)
{
printf("Dat file is NULL!\n");
return -1;
}
for (i = 0; i < dat_num;)
{
fprintf(fp, "%02c", dat[i++]);
if(i % 4 == 0)
fprintf(fp, "\n");
}
fprintf(fp, "\n");
#ifdef DEBUG
for (i = 0; i < dat_num; i++)
{
for (j = 0; j < 4; j++)
{
fprintf(fp, "%02x", dat[i * 4 + j]);
}
}
#endif
return 0;
}
//调用写文件
int w_file(const char *filename, const char *mode, char *dat, int dat_num)
{
FILE *fp;
fp = NULL;
fp = fopen(filename, mode);
if(!fp)
{
printf("Fopen file error!\n");
return -1;
}
w_printf(fp, dat, dat_num);
fclose(fp);
return 0;
}
头文件的调用
#include "stdio.h"
int w_printf(FILE *fp, char *dat, int dat_num);
int w_file(const char *filename, const char *mode, char *dat, int dat_num);
主函数的测试
#include "stdio.h"
#include "./file_IO.h"
int main(int argc, char **argv)
{
const char *filename = "./test.txt";
const char *mode = "wb+";
char *dat = "ago asoguhaiggfasuihgaogbv aooaufouygafkjvchbljzvbanfvkjcb";
int dat_num = 0;
while(dat[dat_num++] != '\0');
w_file(filename, mode, dat, dat_num);
return 0;
}
Makefile文件的编写
all:
gcc -g -Wall -o test file_test.c file_IO.c
clean:
rm -f test
执行的结果
结束语
如有问题,欢迎一同讨论解决!