前言
- 工作太忙了,先不写介绍了,功能都在程序介绍里;
源程序
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
int is_in(char *s, char *c);
char filename[50];
int creat_now_file( char * path,char * prefix, char * file_path);
int main(int argc, char *argv[])
{
char file_path[50];
if( creat_now_file("/online/miss_log/","main",file_path) == 0 )
{
printf("文件%s创建成功!\n",file_path);
}
else
{
printf("文件创建失败!!!\n");
}
return 0;
}
int creat_now_file( char * file_path_profix,char * file_name_prefix, char * file_path)
{
unsigned int max = 0,min = 0,equal_file_name_count = 0,i = 0;
static char path[100];
char path_name_temp[100];
DIR *directory_pointer;
struct dirent *entry;
if((directory_pointer=opendir(file_path_profix))==NULL)
{
printf( "%s Error opening \n",file_path_profix );
return -1;
}
else
{
unsigned int postfix_value;
while((entry=readdir(directory_pointer))!=NULL)
{
memset( path_name_temp,'\0',sizeof( path_name_temp ) );
strcat(path_name_temp,file_name_prefix);
strcat(path_name_temp,"%u");
if(is_in(entry->d_name,file_name_prefix)==1)
{
printf("%s\n",entry-> d_name);
if( sscanf(entry->d_name,path_name_temp,&postfix_value) == 1 )
{
if( i == 0)
{
min = postfix_value;
max = postfix_value;
i = 1;
}
if( postfix_value <= min ) min = postfix_value;
if( postfix_value >= max) max = postfix_value;
}
}
}
closedir(directory_pointer);
}
printf("文件名后缀最大值和最小值:max == %u min == %u\n",max,min);
memset( path,'\0',sizeof( path ) );
memset( path_name_temp,'\0',sizeof( path_name_temp ) );
strcat(path_name_temp,file_path_profix);
strcat(path_name_temp,file_name_prefix);
strcat(path_name_temp,"%u");
sprintf(path,path_name_temp,max+1);
FILE *now_file = fopen(path,"w");
if( now_file == NULL)
{
printf("文件创建失败!!!\n");
return -2;
}
fclose(now_file);
strcpy(file_path,path);
if( max - min > 9)
{
memset( path,'\0',sizeof( path ) );
memset( path_name_temp,'\0',sizeof( path_name_temp ) );
strcat(path_name_temp,file_path_profix);
strcat(path_name_temp,file_name_prefix);
strcat(path_name_temp,"%u");
sprintf(path,path_name_temp,min);
if( remove(path) != 0 )
{
printf("最小文件删除失败!!!\n");
return -3;
}
}
return 0;
}
int is_in(char *s, char *c)
{
int i=0,j=0,flag=-1;
while(i<strlen(s) && j<strlen( c ))
{
if(s[i] == c[j])
{
i++;
j++;
}
else
{
i=i-j+1;
j=0;
}
if(j==strlen( c ))
{
flag=1;
break;
}
}
return flag;
}