File: mkbackup.c

package info (click to toggle)
loki 2.4.7.4-12
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,172 kB
  • sloc: ansic: 38,653; yacc: 4,974; lex: 946; makefile: 333; sh: 100
file content (110 lines) | stat: -rw-r--r-- 2,219 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <config.h>

#include <stdlib.h>
#include <string.h>
#ifdef USE_DMALLOC
#include <dmalloc.h>
#endif
#include <stdio.h>
#include <math.h>
#include <glob.h>
#include <sys/stat.h>

#include "libhdr.h"

struct bkfile {
	char *name;
	int num;
};

static int cmp_func(const void *s1,const void *s2) 
{
	int i,j,k;
	
	i=((struct bkfile *)s1)->num;
	j=((struct bkfile *)s2)->num;
	if(i<j) k=1;
	else if(i>j) k=-1;
	else k=0;
	return k;
}

int mkbackup(const char *fname,int nback) 
{
	int i=0,j,k,k1,k2;
	char *buf,*p,*p1;
	struct stat sbuf;
	struct bkfile *bkfiles;
	glob_t globbuf;
	
	if(!fname) {
		(void)fprintf(stderr,"mkbackup(): NULL filename\n");
		return -1;
	}
	if(nback<1) {
		(void)fprintf(stderr,"mkbackup(): invalid backup number\n");
		return -1;
	}
	if(nback==1) {
		if(!stat(fname,&sbuf)) {
			i=1;
			j=(int)strlen(fname);
			buf=(char *)malloc((size_t)j+2);
			if(buf) {
				(void)strcpy(buf,fname);
				buf[j]='~';
				buf[j+1]='\0';
				i=rename(fname,buf);
				free(buf);
			}
			if(i) (void)fprintf(stderr,"mkbackup(): Couldn't rename old seedfile\n");
		}
	} else {
		j=(int)strlen(fname);
		buf=malloc((size_t)j+2);
		i=1;
		if(buf) {
			(void)strcpy(buf,fname);
			buf[j]='*';
			buf[j+1]='\0';
			globbuf.gl_offs=2;
			(void)glob(buf,0,NULL,&globbuf);
			free(buf);
			if(globbuf.gl_pathc) {
				bkfiles=malloc(sizeof(struct bkfile)*globbuf.gl_pathc);
				if(bkfiles) {
					for(k=k1=0;k<(int)globbuf.gl_pathc;k++) {
						p=globbuf.gl_pathv[k];
						if(p[j]=='~') {
							k2=(int)strtol(p+j+1,&p1,10);
							if(k2>0 && k2<nback && *p1++=='~' && *p1=='\0') {
								bkfiles[k1].name=p;
								bkfiles[k1++].num=k2;
							}
						} else if(p[j]=='\0') {
							bkfiles[k1].name=p;
							bkfiles[k1++].num=0;
						}
					}
					if(k1) {
						qsort(bkfiles,(size_t)k1,sizeof(struct bkfile),cmp_func);
						k2=1+(int)(log((double)nback)/log(10.0));
						buf=malloc((size_t)(k2+3+j));
						if(buf) {
							for(k=0;k<k1;k++) {
								(void)sprintf(buf,"%s~%d~",fname,bkfiles[k].num+1);
								i=rename(bkfiles[k].name,buf);
								if(i) break;
							}
							free(buf);
						}
					} else i=0;
					free(bkfiles);
				}
			} else i=0;
 			globfree(&globbuf);
		}
	}
	return i;
}