Source

lrc / src / Utils.cxx

//      Utils.cxx
//
//      Copyright 2011 Andreas Tscharner <andy@vis.ethz.ch>
//
//      This program is free software; you can redistribute it and/or modify
//      it under the terms of the GNU Lesser General Public License as
//      published by the Free Software Foundation; either version 3 of the
//      License, or (at your option) any later version.
//
//      This program is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU General Public License for more details.
//
//      You should have received a copy of the GNU Lesser General Public
//      License along with this program; if not, write to the Free Software
//      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
//      MA 02110-1301, USA.


#include <string.h>
#include <stdio.h>
#include <sys/stat.h>
#include "Utils.hxx"


bool file_exists(const char *p_filename)
{
	struct stat fInfo;


	return !(stat(p_filename, &fInfo));
};

int file_size(const char *p_filename)
{
	struct stat fInfo;
	int statRet;


	statRet = stat(p_filename, &fInfo);
	if (statRet) {
		DEBUG_PRINT(("stat error on \"%s\": %d\n", p_filename, statRet))
		return -1;
	};
	return fInfo.st_size;
};

char *get_extension(char *p_filename)
{
	return strrchr(p_filename, '.');
};

char *replace_extension(char *p_filename, char *p_newExt)
{
	char *retStr = NULL;
	char *tmpStr = NULL;
	char *oldExt;
	size_t sLen = 0;
	size_t tLen = 0;


	DEBUG_PRINT(("Filename: %s; new extension: %s\n", p_filename, p_newExt))

	oldExt = strrchr(p_filename, '.');
	if (!oldExt) {
		sLen = strlen(p_filename) + strlen(p_newExt) + 1;
		retStr = new char[sLen];
		snprintf(retStr, sLen, "%s%s", p_filename, p_newExt);

		DEBUG_PRINT(("Filename had no extension. Appending new one: %s\n", retStr))
		return retStr;
	};

	sLen = strlen(p_filename) - strlen(oldExt) + strlen(p_newExt) + 1;
	retStr = new char[sLen];
	tLen = strlen(p_filename) - strlen(oldExt);
	tmpStr = new char[tLen];
	strncpy(tmpStr, p_filename, tLen);
	snprintf(retStr, sLen, "%s%s", tmpStr, p_newExt);
	delete[] tmpStr;

	DEBUG_PRINT(("Replaced old extension with new one: %s\n", retStr))
	return retStr;
};

void delete_list(unsigned char **p_dataList, unsigned int p_dataSize)
{
	for (int i = (p_dataSize-1); i >= 0; i--)
		delete[] p_dataList[i];
	delete[] p_dataList;
};

int password_len(const unsigned char *p_password)
{
	int uCharCount = 0;
	unsigned char *passRun;


	if (!p_password) {
		return -1;
	};

	passRun = (unsigned char *)p_password;
	while (*passRun) {
		uCharCount++;
		passRun++;
	};
	return uCharCount;
};