⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cache.c

📁 一个C语言的聊天室源代码
💻 C
字号:
/*
	Version: 0.2.0(stable)
	Author: Computer_xu
	Email: Computer_xu@sina.com
	HomePage: http://www.socketchat.com
	LastModify: 2001-05-07 (yyyy-mm-dd)
*/


#include "cache.h"

pthread_mutex_t cache_mutex=PTHREAD_MUTEX_INITIALIZER;

/* 把文件增加到cache */
char *AddToCache(char *filename,unsigned long *size)
{
        FILE *fp;
        DocCache *p1,*p2;
        unsigned long filesize;
	struct stat filestat;

        pthread_mutex_lock(&cache_mutex);
        fp=fopen(filename,"rb");
	if(fp==NULL)
	{
		pthread_mutex_unlock(&cache_mutex);
		return(NULL);
	}

        p1=(DocCache *)Malloc(sizeof(DocCache));
        p1->filename=(char *)Malloc(Strlen(filename)+1);
        strcpy(p1->filename,filename);
        p1->next=NULL;
        if( sysinfo.Cache_HEAD==NULL )
        {
                sysinfo.Cache_HEAD=p1;
        }
        else
        {
                p2=sysinfo.Cache_HEAD;
                while(p2->next!=NULL) p2=p2->next;
                p2->next=p1;
        }
	fstat(fileno(fp),&filestat);
	p1->lasttime=filestat.st_mtime;
	p1->size=filesize=(*size)=filestat.st_size;
        p1->filedata=(char *)Malloc(filesize+1);
        fread(p1->filedata,filesize,1,fp);
        p1->filedata[filesize]='\0';
        fclose(fp);
        /* printf("Add %s to cache , size = %ld\n",filename,filesize); */
        pthread_mutex_unlock(&cache_mutex);
        return(p1->filedata);
}
/* 删除一个Cache节点 */
void DelFromCache(char *filename)
{
        DocCache *p1,*p2;

        pthread_mutex_lock(&cache_mutex);
	p1=p2=sysinfo.Cache_HEAD;
	while( p1!=NULL )
	{
		if( StrCmp(p1->filename,filename)==0 )
		{
			Free(p1->filename);
			Free(p1->filedata);
			if( p1==sysinfo.Cache_HEAD )	sysinfo.Cache_HEAD=p1->next;
			else				p2->next=p1->next;
			Free(p1);
			break;
		}
		p2=p1;
		p1=p1->next;
	}
        pthread_mutex_unlock(&cache_mutex);
}
/* 获取文件内容 */
char *GetFileData(char *filename,unsigned long *size)
{
        DocCache *p1;
	struct stat filestat;

        if( sysinfo.Cache_HEAD!=NULL )
        {
                p1=sysinfo.Cache_HEAD;
                while(p1!=NULL)
                {
                        if( StrCmp(p1->filename,filename)==0 )
			{
				if( stat(filename,&filestat)==0 )
				{
					if( filestat.st_mtime==p1->lasttime )
					{
						(*size)=p1->size;
						return(p1->filedata);
					}
					else
					{
						/* printf("Time Changed %ld, %ld\n",filestat.st_atime,p1->lasttime); */
						DelFromCache(filename);
						break;
					}
				}
				else
				{
					DelFromCache(filename);
					return(NULL);
				}
			}
                        p1=p1->next;
                }
        }
        return(AddToCache(filename,size));
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -