Esempio n. 1
0
file_cache_entry_t* file_cache_put(const char* file_path) {
	static size_t file_cache_head = 0;

	int file_fd = -1;
	off_t file_len;
	char* file_buf = NULL;
	int nbytes;
	file_cache_entry_t* old_entry = NULL;

	// Allocate a new entry
	file_cache_entry_t* new_entry = (file_cache_entry_t*)
						malloc(sizeof(*new_entry));
	if (new_entry == NULL) goto exit; // out of memory

	// Copy the file path
	new_entry->file_path = strdup(file_path);
	if (new_entry->file_path == NULL) goto exit; // out of memory

	// Open the file
	file_fd= open(file_path, O_RDONLY);
	if (file_fd < 0) goto exit;

	// Determine the length of the file
	file_len = lseek(file_fd, (off_t)0, SEEK_END);
	file_buf = new_entry->data.buf = (char*) malloc(file_len);
	if (file_buf == NULL) goto exit;
	new_entry->data.len = file_len;

	// Cache the content of the file
	lseek(file_fd, (off_t)0, SEEK_SET);
	while ((nbytes = read(file_fd, file_buf, file_len)) > 0) {
		file_buf += nbytes;
		file_len -= nbytes;
	}
	if (nbytes < 0) goto exit;

	// Put the new entry in the cache
	old_entry = file_cache[file_cache_head];
	if (old_entry != NULL) file_cache_evict(old_entry);
	file_cache[file_cache_head++] = new_entry;
	if (file_cache_head == MAX_CACHED_FILES) file_cache_head = 0;

	close(file_fd);
	return new_entry;
exit:
	if (file_fd >= 0) close(file_fd);
	free(file_buf);
	if (new_entry) free(new_entry->file_path);
	free(new_entry);
	return NULL;
}
Esempio n. 2
0
int main()
{
  printf("Simple File Caching!\n");
  char *file[] = {"file1", "file2", "file3", "file4"};

  file_cache *cache = file_cache_construct(4);

  file_cache_pin_files(cache, (const char **)file, 3);
  file_cache_unpin_files(cache, (const char **) file, 2);
  file_cache_evict(cache); 

  printf("Destroying cache!\n");
  file_cache_destroy(cache);

  return 0;
}