Home » Tag » External Text File Source - Version 2.0.43

Tag

External Text File Source - Version 2.0.43

The code below is that used to add the -f switch functionality, which allows users to pass the path to a text file, the contents of which are read as the tag value.

I would be very interested to hear about improvements to this code.

NB: This code is an improvement to that used in version 2.0.40b2. Thanks to Niko Korhonen for his suggestions for improvement. I feel a lot happier with it now it has been scrutinised by a competent C++ programmer. The code now opens the file in binary mode, negating the need for me to replace carriage returns, and also correctly stores the array filearg on the heap, and not the stack.

This code is also an improvement to that used in version 2.0.40b4. There is no longer a 10KB limit on the filearg array. Not only does this mean that you can add files larger than 10KB (which probably isn't really a good idea), it also means that less memory is reserved if only adding a small amount of text.

Obviously the variable new_argv[i] contains the parameter, e.g.: "cuesheet=C:\CDImage.ape.cue"


char * file_name;
size_t itemlen;
FILE * stream;
int ch;
int j;
char * filearg;

// do other stuff

// check parameter is of format "<tag>=<file>"
if ( !proper_tag ( new_argv[i] ) ) {
	fprintf ( stderr, "%s: incorrect format - expecting <item=x>.\n", new_argv[i] );
	exit (1);
}

// get filename from parameter (part after '=')
file_name = strchr ( new_argv[i], '=' ) + 1;

// get length of tag name
itemlen = file_name - new_argv[i] - 1;

// check file exists
if ( (stream = fopen ( file_name, "rb" ) ) == NULL ) {
	fprintf ( stderr, "%s: failed to open file for for reading.\n", file_name );
	exit (1);
}

// get file size
long file_size = get_filesize(stream);

// create dynamic array and set filearg to "<tag>="
filearg = (char *)malloc(file_size + itemlen + 2);
strncpy(filearg, new_argv[i], itemlen + 1);

// start filling char array after "="
j = itemlen + 1;

// read text from file
while ( (ch = fgetc (stream)) != EOF ) {

	// add read character to array
	filearg[j] = (char)ch;
	j++;
}

// terminate will null char
filearg[j] = '\0';

// close stream
fclose (stream);

// do other stuff

//free the array
free ( filearg );

// do other stuff

long get_filesize (FILE *f)
{

    long cur_pos, length;
    cur_pos = ftell(f);
    fseek(f, 0, SEEK_END);
    length = ftell(f);
    fseek(f, cur_pos, SEEK_SET);
    return length;
}


Created using C++2HTML

Top


Visit the WavPack Website foobar2000 audio player

Home  |  Tag  |  Wapet  |  Contact


This document has been printed from http://www.synthetic-soul.co.uk/