linux c读写操作复制文件
代码
6.27
1.增加写入图片数量限制
2.超过数量限制则从编号0开始覆盖写入
3.设备重启后根据文件夹存在文件数依次继续写入
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include <dirent.h>
#define PIC_PATH "test.jpg"
#define SAVE_DIR "./pic"
#define SAVA_PIC_MAX 30
#define SIZE 1000*1000
//#define SAVE_PATH "home/linux/pic"
extern int errno;
unsigned long get_file_size(const char *path)
{
struct stat statbuff;
if (stat(path, &statbuff) < 0)
{
return -1;
}
else
{
return statbuff.st_size;
}
}
int main()
{
FILE *fp1,*fp2;
int i = 0;
int j = 0;
int count = 0;
char save_path[256];
char * pic;
extern int errno;
pic = (char *)malloc(SIZE);
unsigned long pic_len;
DIR * pDir = NULL;
struct dirent * pEnt = NULL;
if (NULL == pic)
{
printf("malloc failed,error_num is %d ,error_msg is %s \n", errno, strerror(errno));
return -1;
}
else
{
memset(pic,0,SIZE);
printf("malloc seccess!\n");
}
if ((fp1 = fopen(PIC_PATH,"r+")) == NULL)
{
printf("open test.jpg failed,error_num is %d ,error_msg is %s \n", errno, strerror(errno));
return -1;
}
if (0 > (pic_len = get_file_size(PIC_PATH)))
{
printf("get file size failed!\n");
}
else
{
printf("file size is %ld \n",pic_len);
}
while (!feof(fp1))
{
if ((count = fread(pic,sizeof(char),pic_len+1,fp1)) < 0)
{
printf("fread pic error,error_num is %d ,error_msg is %s \n", errno, strerror(errno));
return -1;
}
printf("pic_len is %d",count);
printf("read seccess\n");
fflush(fp1);
}
fclose(fp1);
while(j<40)
{
count = 0;
if (i == 0)
{
pDir = opendir(SAVE_DIR);
if(!pDir)
{
if (mkdir(SAVE_DIR, 0777) < 0)
{
if (EEXIST != errno)
{
printf("mkdir %s, errno: %d(%s)\n", SAVE_DIR, errno, strerror(errno));
closedir(pDir);
}
}
}
else
{
while (1)
{
pEnt = readdir(pDir);
if(pEnt != NULL)
{
if(strcmp(pEnt->d_name, "..")==0 || strcmp(pEnt->d_name, ".")==0)
{
continue;
}
printf("count is %d\n",count);
count++;
}
else
{
break;
}
}
printf("path contain %d pic_file\n", count);
if ( SAVA_PIC_MAX <= count || 0 == count)
{
i = 0;
}
else
{
i = count - 1;
}
closedir(pDir);
sync();
}
}
sprintf(save_path,"./pic/pic_%d.jpg",i);
if ((fp2 = fopen(save_path,"w+")) == NULL)
{
printf("open pic_%d.jpg failed,error_num is %d ,error_msg is %s \n", i, errno, strerror(errno));
return -1;
}
else
{
printf("create pic_%d.jpg ok! \n",i);
}
count = fwrite(pic,sizeof(char),pic_len,fp2);
if (count < 0)
{
printf("fwrite pic error,error_num is %d ,error_msg is %s \n", errno, strerror(errno));
return -1;
}
else
{
printf("write size is %d \n",count);
}
fflush(fp2);
printf("write pic_%d.jpg ok!\n",i);
fclose(fp2);
if (i < SAVA_PIC_MAX - 1)
{
i++;
}
else
{
i = 0;
}
j++;
}
return 0;
}