You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ffdb/fs_list.c

68 lines
1.2 KiB
C

#include "fs_list.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/file.h>
int fs_list_get( const char* filename )
{
FILE* f;
int pos = 0;
f = fopen(filename,"r");
if( !f ) {
printf( "Failed to open %s, initializing at 0\n", filename );
fs_list_set(filename,0);
return 0;
}
fscanf( f, "%d", &pos );
fclose(f);
return pos;
}
void fs_list_set( const char* path, int value )
{
char buffer[512];
snprintf( buffer,sizeof(buffer), "%s.lock", path );
int fd = open( buffer, O_CREAT );
if( !fd ) { return; }
flock( fd, LOCK_EX );
char tmp_filename[512];
snprintf( tmp_filename, 512, "%s.tmp", path );
FILE* f = fopen(tmp_filename,"w");
if( !f ) { return; }
fprintf( f, "%d", value );
fclose(f);
rename( tmp_filename, path );
flock( fd, LOCK_UN );
close(fd);
}
int fs_list_inc( const char* path )
{
char buffer[512];
snprintf( buffer,sizeof(buffer), "%s.lock", path );
int fd = open( buffer, O_CREAT );
flock( fd, LOCK_EX );
int value = fs_list_get( path ) + 1;
char tmp_filename[512];
snprintf( tmp_filename, 512, "%s.tmp", path );
FILE* f = fopen(tmp_filename,"w");
fprintf( f, "%d", value );
fclose(f);
rename( tmp_filename, path );
flock( fd, LOCK_UN );
close(fd);
return value;
}