Package: libmagic-dev
Version: 5.04-1
Severity: normal

The following program does a magic_file() call and then strncmp compares
the result. When the result string is copied, this works fine, but when 
the resulting 'const char*' is used directly, the strncmp gives incorrect
results.

I'm not sure whether this is a bug, that some documentation is missing
on the storage persistence of the result string, or maybe I overlooked 
something.

Jaap Eldering

-- System Information:
Debian Release: squeeze/sid
  APT prefers testing
  APT policy: (500, 'testing')
Architecture: i386 (x86_64)

Kernel: Linux 2.6.32-trunk-amd64 (SMP w/3 CPU cores)
Locale: LANG=en_US.UTF-8, LC_CTYPE=en_US.UTF-8 (charmap=UTF-8)
Shell: /bin/sh linked to /bin/dash

Versions of packages libmagic-dev depends on:
ii  libmagic1               5.04-1           File type determination library us
ii  zlib1g-dev              1:1.2.3.4.dfsg-3 compression library - development

libmagic-dev recommends no packages.

Versions of packages libmagic-dev suggests:
ii  file                          5.04-1     Determines file type using "magic"

-- no debconf information
#include <stdio.h>
#include <string.h>
#include <magic.h>

int file_istext(char *filename);

int main(int argc, char **argv)
{
	char *filename;

	if ( argc!=2 ) {
		printf("require a filename argument\n");
		return 1;
	}
	filename = argv[1];

	if ( !file_istext(filename) ) {
		printf("file is detected as binary/data\n");
	} else {
		printf("file is detected as text\n");
	}

	return 0;
}

int file_istext(char *filename)
{
	magic_t cookie;
	const char *filetype;
	char *str;
	int res;

	if ( (cookie = magic_open(MAGIC_MIME))==NULL ) goto error;

	if ( magic_load(cookie,NULL)!=0 ) goto error;

	if ( (filetype = magic_file(cookie,filename))==NULL ) goto error;

	// For some reason, strncmp'ing the original return value gives
	// wrong results; making a local copy works.
//	str = strdup(filetype);
	str = filetype;

	printf("mime-type is '%s'\n",str);

	magic_close(cookie);

	res = (strncmp(str,"text/",5)==0);
//	free(str);
	return res;

error:
	printf("error %d: %s\n",magic_errno(cookie),magic_error(cookie));

	return 1; // return 'text' by default on error
}

Reply via email to