1 | // Copyright (c) Athena Dev Teams - Licensed under GNU GPL |
---|
2 | // For more information, see LICENCE in the main folder |
---|
3 | |
---|
4 | #include "../common/cbasetypes.h" |
---|
5 | #include "../common/showmsg.h" |
---|
6 | #include "lock.h" |
---|
7 | |
---|
8 | #include <stdio.h> |
---|
9 | #include <errno.h> |
---|
10 | #include <string.h> |
---|
11 | #ifndef WIN32 |
---|
12 | #include <unistd.h> |
---|
13 | #else |
---|
14 | #include <windows.h> |
---|
15 | #define F_OK 0x0 |
---|
16 | #define R_OK 0x4 |
---|
17 | #endif |
---|
18 | |
---|
19 | #ifndef WIN32 |
---|
20 | #define exists(filename) (!access(filename, F_OK)) |
---|
21 | #else |
---|
22 | // could be speed up maybe? |
---|
23 | int exists(char *file) { |
---|
24 | FILE *fp; |
---|
25 | if ((fp = fopen(file,"r")) && fclose(fp) == 0) return 1; |
---|
26 | return 0; |
---|
27 | } |
---|
28 | #endif |
---|
29 | |
---|
30 | // «Ýt@CÌÛì |
---|
31 | // i«ÝªIíéÜÅAt@CðÛǵĚj |
---|
32 | |
---|
33 | // Vµ¢t@CÌ«ÝJn |
---|
34 | FILE* lock_fopen (const char* filename, int *info) { |
---|
35 | char newfile[512]; |
---|
36 | FILE *fp; |
---|
37 | int no = 0; |
---|
38 | |
---|
39 | // ÀSÈt@CŒðŸéi貫j |
---|
40 | do { |
---|
41 | sprintf(newfile, "%s_%04d.tmp", filename, ++no); |
---|
42 | } while((fp = fopen(newfile,"r")) && (fclose(fp), no < 9999)); |
---|
43 | *info = no; |
---|
44 | return fopen(newfile,"w"); |
---|
45 | } |
---|
46 | |
---|
47 | // t@CðíVt@Cðl[ |
---|
48 | int lock_fclose (FILE *fp, const char* filename, int *info) { |
---|
49 | int ret = 1; |
---|
50 | char newfile[512]; |
---|
51 | char oldfile[512]; |
---|
52 | if (fp != NULL) { |
---|
53 | ret = fclose(fp); |
---|
54 | sprintf(newfile, "%s_%04d.tmp", filename, *info); |
---|
55 | sprintf(oldfile, "%s.bak", filename); // old backup file |
---|
56 | |
---|
57 | if (exists(oldfile)) remove(oldfile); // remove backup file if it already exists |
---|
58 | rename (filename, oldfile); // backup our older data instead of deleting it |
---|
59 | |
---|
60 | // ±Ì^C~OÅ¿éÆÅ«B |
---|
61 | if ((ret = rename(newfile,filename)) != 0) { // rename our temporary file to its correct name |
---|
62 | #if defined(__NETBSD__) || defined(_WIN32) || defined(sun) || defined (_sun) || defined (__sun__) |
---|
63 | ShowError("%s - '"CL_WHITE"%s"CL_RESET"'\n", strerror(errno), newfile); |
---|
64 | #else |
---|
65 | char ebuf[255]; |
---|
66 | ShowError("%s - '"CL_WHITE"%s"CL_RESET"'\n", strerror_r(errno, ebuf, sizeof(ebuf)), newfile); |
---|
67 | #endif |
---|
68 | } |
---|
69 | } |
---|
70 | |
---|
71 | return ret; |
---|
72 | } |
---|