root/src/common/lock.c @ 13

Revision 1, 2.0 kB (checked in by jinshiro, 17 years ago)
Line 
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?
23int 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‚í‚é‚܂ŁA‹Œƒtƒ@ƒCƒ‹‚ð•ÛŠÇ‚µ‚Ä‚š‚­j
32
33// V‚µ‚¢ƒtƒ@ƒCƒ‹‚̏‘‚«ž‚ÝŠJŽn
34FILE* 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ƒ‹‚ðíœ•Vƒtƒ@ƒCƒ‹‚ðƒŠƒl[ƒ€
48int 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}
Note: See TracBrowser for help on using the browser.