Leptonica 1.68
C Image Processing Library

utils.c File Reference

Error, warning and info macros; safe string ops; file <-> memory ops; byte-swapping, file naming and timing ops. More...

#include <string.h>
#include <time.h>
#include <unistd.h>
#include "allheaders.h"
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>

Go to the source code of this file.

Functions

l_int32 returnErrorInt (const char *msg, const char *procname, l_int32 ival)
l_float32 returnErrorFloat (const char *msg, const char *procname, l_float32 fval)
void * returnErrorPtr (const char *msg, const char *procname, void *pval)
void l_error (const char *msg, const char *procname)
void l_errorString (const char *msg, const char *procname, const char *str)
void l_errorInt (const char *msg, const char *procname, l_int32 ival)
void l_errorFloat (const char *msg, const char *procname, l_float32 fval)
void l_warning (const char *msg, const char *procname)
void l_warningString (const char *msg, const char *procname, const char *str)
void l_warningInt (const char *msg, const char *procname, l_int32 ival)
void l_warningInt2 (const char *msg, const char *procname, l_int32 ival1, l_int32 ival2)
void l_warningFloat (const char *msg, const char *procname, l_float32 fval)
void l_warningFloat2 (const char *msg, const char *procname, l_float32 fval1, l_float32 fval2)
void l_info (const char *msg, const char *procname)
void l_infoString (const char *msg, const char *procname, const char *str)
void l_infoInt (const char *msg, const char *procname, l_int32 ival)
void l_infoInt2 (const char *msg, const char *procname, l_int32 ival1, l_int32 ival2)
void l_infoFloat (const char *msg, const char *procname, l_float32 fval)
void l_infoFloat2 (const char *msg, const char *procname, l_float32 fval1, l_float32 fval2)
char * stringNew (const char *src)
l_int32 stringCopy (char *dest, const char *src, l_int32 n)
l_int32 stringReplace (char **pdest, const char *src)
l_int32 stringLength (const char *src, size_t size)
l_int32 stringCat (char *dest, size_t size, const char *src)
char * stringJoin (const char *src1, const char *src2)
char * stringReverse (const char *src)
char * strtokSafe (char *cstr, const char *seps, char **psaveptr)
l_int32 stringSplitOnToken (char *cstr, const char *seps, char **phead, char **ptail)
char * stringRemoveChars (const char *src, const char *remchars)
l_int32 stringFindSubstr (const char *src, const char *sub, l_int32 *ploc)
char * stringReplaceSubstr (const char *src, const char *sub1, const char *sub2, l_int32 *pfound, l_int32 *ploc)
char * stringReplaceEachSubstr (const char *src, const char *sub1, const char *sub2, l_int32 *pcount)
NUMAarrayFindEachSequence (const l_uint8 *data, l_int32 datalen, const l_uint8 *sequence, l_int32 seqlen)
l_int32 arrayFindSequence (const l_uint8 *data, l_int32 datalen, const l_uint8 *sequence, l_int32 seqlen, l_int32 *poffset, l_int32 *pfound)
void * reallocNew (void **pindata, l_int32 oldsize, l_int32 newsize)
l_uint8l_binaryRead (const char *filename, size_t *pnbytes)
l_uint8l_binaryReadStream (FILE *fp, size_t *pnbytes)
l_int32 l_binaryWrite (const char *filename, const char *operation, void *data, size_t nbytes)
size_t nbytesInFile (const char *filename)
size_t fnbytesInFile (FILE *fp)
l_uint8l_binaryCopy (l_uint8 *datas, size_t size)
l_int32 fileCopy (const char *srcfile, const char *newfile)
l_int32 fileConcatenate (const char *srcfile, const char *destfile)
l_int32 fileAppendString (const char *filename, const char *str)
l_int32 filesAreIdentical (const char *fname1, const char *fname2, l_int32 *psame)
l_uint16 convertOnLittleEnd16 (l_uint16 shortin)
l_uint16 convertOnBigEnd16 (l_uint16 shortin)
l_uint32 convertOnLittleEnd32 (l_uint32 wordin)
l_uint32 convertOnBigEnd32 (l_uint32 wordin)
FILE * fopenReadStream (const char *filename)
FILE * fopenWriteStream (const char *filename, const char *modestring)
FILE * lept_fopen (const char *filename, const char *mode)
l_int32 lept_fclose (FILE *fp)
void * lept_calloc (size_t nmemb, size_t size)
void lept_free (void *ptr)
l_int32 lept_mkdir (const char *subdir)
l_int32 lept_rmdir (const char *subdir)
l_int32 lept_rm (const char *subdir, const char *filename)
l_int32 lept_mv (const char *srcfile, const char *newfile)
l_int32 lept_cp (const char *srcfile, const char *newfile)
l_int32 splitPathAtDirectory (const char *pathname, char **pdir, char **ptail)
l_int32 splitPathAtExtension (const char *pathname, char **pbasename, char **pextension)
char * pathJoin (const char *dir, const char *fname)
char * genPathname (const char *dir, const char *fname)
char * genTempFilename (const char *dir, const char *tail, l_int32 usetime, l_int32 usepid)
l_int32 extractNumberFromFilename (const char *fname, l_int32 numpre, l_int32 numpost)
l_int32 genRandomIntegerInRange (l_int32 range, l_int32 seed, l_int32 *pval)
char * getLeptonicaVersion ()
void startTimer (void)
l_float32 stopTimer (void)
L_TIMER startTimerNested (void)
l_float32 stopTimerNested (L_TIMER rusage_start)
void l_getCurrentTime (l_int32 *sec, l_int32 *usec)
char * l_getFormattedDate ()
l_uint8arrayRead (const char *fname, l_int32 *pnbytes)
l_uint8arrayReadStream (FILE *fp, l_int32 *pnbytes)

Variables

static const char sepchar = '/'
static struct rusage rusage_before
static struct rusage rusage_after

Detailed Description

Error, warning and info macros; safe string ops; file <-> memory ops; byte-swapping, file naming and timing ops.

     Error, warning and info procs; all invoked by macros
         l_int32    returnErrorInt()
         l_float32  returnErrorFloat()
         void      *returnErrorPtr()
         void       l_error()
         void       l_errorString()
         void       l_errorInt()
         void       l_errorFloat()
         void       l_warning()
         void       l_warningString()
         void       l_warningInt()
         void       l_warningInt2()
         void       l_warningFloat()
         void       l_warningFloat2()
         void       l_info()
         void       l_infoString()
         void       l_infoInt()
         void       l_infoInt2()
         void       l_infoFloat()
         void       l_infoFloat2()

     Safe string procs
         char      *stringNew()
         l_int32    stringCopy()
         l_int32    stringReplace()
         l_int32    stringLength()
         l_int32    stringCat()
         char      *stringJoin()
         char      *stringReverse()
         char      *strtokSafe()
         l_int32    stringSplitOnToken()

     Find and replace string and array procs
         char      *stringRemoveChars()
         l_int32    stringFindSubstr()
         char      *stringReplaceSubstr()
         char      *stringReplaceEachSubstr()
         NUMA      *arrayFindEachSequence()
         l_int32    arrayFindSequence()

     Safe realloc
         void      *reallocNew()

     Read and write between file and memory
         l_uint8   *l_binaryRead()
         l_uint8   *l_binaryReadStream()
         l_int32    l_binaryWrite()
         l_int32    nbytesInFile()
         l_int32    fnbytesInFile()

     Copy in memory
         l_uint8   *l_binaryCopy()

     File copy operations
         l_int32    fileCopy()
         l_int32    fileConcatenate()
         l_int32    fileAppendString()

     Test files for equivalence
         l_int32    filesAreIdentical()

     Byte-swapping data conversion
         l_uint16   convertOnBigEnd16()
         l_uint32   convertOnBigEnd32()
         l_uint16   convertOnLittleEnd16()
         l_uint32   convertOnLittleEnd32()

     Opening file streams
         FILE      *fopenReadStream()
         FILE      *fopenWriteStream()

     Functions to avoid C-runtime boundary crossing with Windows DLLs
         FILE      *lept_fopen()
         l_int32    lept_fclose()
         void       lept_calloc()
         void       lept_free()

     Cross-platform file system operations
         l_int32    lept_mkdir()
         l_int32    lept_rmdir()
         l_int32    lept_mv()
         l_int32    lept_rm()
         l_int32    lept_cp()

     File name operations
         l_int32    splitPathAtDirectory()
         l_int32    splitPathAtExtension()
         char      *pathJoin()
         char      *genPathname()
         char      *genTempFilename()
         l_int32    extractNumberFromFilename()

     Generate random integer in given range
         l_int32    genRandomIntegerInRange()

     Leptonica version number
         char      *getLeptonicaVersion()

     Timing
         void       startTimer()
         l_float32  stopTimer()
         L_TIMER    startTimerNested()
         l_float32  stopTimerNested()
         void       l_getCurrentTime()
         void       l_getFormattedDate()

     Deprecated binary read functions  (don't use these!)
         l_uint8   *arrayRead()
         l_uint8   *arrayReadStream()


Notes on cross-platform development
-----------------------------------
(1) With the exception of splitPathAtDirectory() and
    splitPathAtExtension(), all input pathnames must have unix separators.
(2) The conversion from unix to windows pathnames happens in genPathname().
(3) Use fopenReadStream() and fopenWriteStream() to open files,
    because these use genPathname() to find the platform-dependent
    filenames.  Likewise for l_binaryRead() and l_binaryWrite().
(4) For moving, copying and removing files and directories,
    use the lept_*() file system shell wrappers:
       lept_mkdir(), lept_rmdir(), lept_mv(), lept_rm() and lept_cp().
(5) Use the lept_*() C library wrappers:
       lept_fopen(), lept_fclose(), lept_calloc() and lept_free().

Definition in file utils.c.


Function Documentation

l_int32 returnErrorInt ( const char *  msg,
const char *  procname,
l_int32  ival 
)

returnErrorInt()

Input: msg (error message) procname ival (return val) Return: ival (typically 1)

Definition at line 186 of file utils.c.

l_float32 returnErrorFloat ( const char *  msg,
const char *  procname,
l_float32  fval 
)

returnErrorFloat()

Input: msg (error message) procname fval (return val) Return: fval

Definition at line 204 of file utils.c.

void* returnErrorPtr ( const char *  msg,
const char *  procname,
void *  pval 
)

returnErrorPtr()

Input: msg (error message) procname pval (return val) Return: pval (typically null)

Definition at line 222 of file utils.c.

void l_error ( const char *  msg,
const char *  procname 
)

l_error()

Input: msg (error message) procname

Definition at line 238 of file utils.c.

void l_errorString ( const char *  msg,
const char *  procname,
const char *  str 
)

l_errorString()

Input: msg (error message; must include 's') procname str (embedded in error message via s)

Definition at line 254 of file utils.c.

References L_Memstream::bufsize, CALLOC, FREE, L_ERROR, and NULL.

void l_errorInt ( const char *  msg,
const char *  procname,
l_int32  ival 
)

l_errorInt()

Input: msg (error message; must include 'd') procname ival (embedded in error message via d)

Definition at line 289 of file utils.c.

References L_Memstream::bufsize, CALLOC, FREE, L_ERROR, and NULL.

void l_errorFloat ( const char *  msg,
const char *  procname,
l_float32  fval 
)

l_errorFloat()

Input: msg (error message; must include 'f') procname fval (embedded in error message via f)

Definition at line 323 of file utils.c.

References L_Memstream::bufsize, CALLOC, FREE, L_ERROR, and NULL.

void l_warning ( const char *  msg,
const char *  procname 
)

l_warning()

Input: msg (warning message) procname

Definition at line 356 of file utils.c.

void l_warningString ( const char *  msg,
const char *  procname,
const char *  str 
)

l_warningString()

Input: msg (warning message; must include 's') procname str (embedded in warning message via s)

Definition at line 372 of file utils.c.

References L_Memstream::bufsize, CALLOC, FREE, L_ERROR, and NULL.

void l_warningInt ( const char *  msg,
const char *  procname,
l_int32  ival 
)

l_warningInt()

Input: msg (warning message; must include 'd') procname ival (embedded in warning message via d)

Definition at line 407 of file utils.c.

References L_Memstream::bufsize, CALLOC, FREE, L_ERROR, and NULL.

void l_warningInt2 ( const char *  msg,
const char *  procname,
l_int32  ival1,
l_int32  ival2 
)

l_warningInt2()

Input: msg (warning message; must include 'd') procname ival1, ival2 (two args, embedded in message via d)

Definition at line 441 of file utils.c.

References L_Memstream::bufsize, CALLOC, FREE, L_ERROR, and NULL.

void l_warningFloat ( const char *  msg,
const char *  procname,
l_float32  fval 
)

l_warningFloat()

Input: msg (warning message; must include 'f') procname fval (embedded in warning message via f)

Definition at line 476 of file utils.c.

References L_Memstream::bufsize, CALLOC, FREE, L_ERROR, and NULL.

void l_warningFloat2 ( const char *  msg,
const char *  procname,
l_float32  fval1,
l_float32  fval2 
)

l_warningFloat2()

Input: msg (warning message; must include 'f') procname fval1, fval2 (two args, embedded in message via f)

Definition at line 510 of file utils.c.

References L_Memstream::bufsize, CALLOC, FREE, L_ERROR, and NULL.

void l_info ( const char *  msg,
const char *  procname 
)

l_info()

Input: msg (info message) procname

Definition at line 544 of file utils.c.

void l_infoString ( const char *  msg,
const char *  procname,
const char *  str 
)

l_infoString()

Input: msg (info message; must include 's') procname str (embedded in warning message via s)

Definition at line 560 of file utils.c.

References L_Memstream::bufsize, CALLOC, FREE, L_ERROR, and NULL.

void l_infoInt ( const char *  msg,
const char *  procname,
l_int32  ival 
)

l_infoInt()

Input: msg (info message; must include 'd') procname ival (embedded in info message via d)

Definition at line 594 of file utils.c.

References L_Memstream::bufsize, CALLOC, FREE, L_ERROR, and NULL.

void l_infoInt2 ( const char *  msg,
const char *  procname,
l_int32  ival1,
l_int32  ival2 
)

l_infoInt2()

Input: msg (info message; must include two 'd') procname ival1, ival2 (two args, embedded in info message via d)

Definition at line 628 of file utils.c.

References L_Memstream::bufsize, CALLOC, FREE, L_ERROR, and NULL.

void l_infoFloat ( const char *  msg,
const char *  procname,
l_float32  fval 
)

l_infoFloat()

Input: msg (info message; must include 'f') procname fval (embedded in info message via f)

Definition at line 663 of file utils.c.

References L_Memstream::bufsize, CALLOC, FREE, L_ERROR, and NULL.

void l_infoFloat2 ( const char *  msg,
const char *  procname,
l_float32  fval1,
l_float32  fval2 
)

l_infoFloat2()

Input: msg (info message; must include two 'f') procname fval1, fval2 (two args, embedded in info message via f)

Definition at line 697 of file utils.c.

References L_Memstream::bufsize, CALLOC, FREE, L_ERROR, and NULL.

l_int32 stringCopy ( char *  dest,
const char *  src,
l_int32  n 
)

stringCopy()

Input: dest (existing byte buffer) src string (can be null) n (max number of characters to copy) Return: 0 if OK, 1 on error

Notes: (1) Relatively safe wrapper for strncpy, that checks the input, and does not complain if is null or
< 1. If
< 1, this is a no-op. (2) needs to be at least
bytes in size. (3) We don't call strncpy() because valgrind complains about use of uninitialized values.

Definition at line 771 of file utils.c.

References ERROR_INT, and PROCNAME.

Referenced by genPathname(), l_binaryWrite(), stringJoin(), stringNew(), stringReplace(), and strtokSafe().

l_int32 stringReplace ( char **  pdest,
const char *  src 
)

stringReplace()

Input: &dest string (<return> copy) src string Return: 0 if OK; 1 on error

Notes: (1) Frees any existing dest string (2) Puts a copy of src string in the dest (3) If either or both strings are null, does something reasonable.

Definition at line 806 of file utils.c.

References CALLOC, ERROR_INT, FREE, NULL, PROCNAME, and stringCopy().

Referenced by gplotRead(), main(), pixAddText(), pixSetText(), and selSetName().

l_int32 stringLength ( const char *  src,
size_t  size 
)

stringLength()

Input: src string (can be null or null-terminated string) size (size of src buffer) Return: length of src in bytes.

Notes: (1) Safe implementation of strlen that only checks size bytes for trailing NUL. (2) Valid returned string lengths are between 0 and size - 1. If size bytes are checked without finding a NUL byte, then an error is indicated by returning size.

Definition at line 849 of file utils.c.

References ERROR_INT, PROCNAME, and size.

Referenced by stringCat().

l_int32 stringCat ( char *  dest,
size_t  size,
const char *  src 
)

stringCat()

Input: dest (null-terminated byte buffer) size (size of dest) src string (can be null or null-terminated string) Return: number of bytes added to dest; -1 on error

Notes: (1) Alternative implementation of strncat, that checks the input, is easier to use (since the size of the dest buffer is specified rather than the number of bytes to copy), and does not complain if is null. (2) Never writes past end of dest. (3) If it can't append src (an error), it does nothing. (4) N.B. The order of 2nd and 3rd args is reversed from that in strncat, as in the Windows function strcat_s().

Definition at line 888 of file utils.c.

References ERROR_INT, PROCNAME, and stringLength().

Referenced by genPathname(), and genTempFilename().

char* stringJoin ( const char *  src1,
const char *  src2 
)

stringJoin()

Input: src1 string (<optional> can be null) src2 string (<optional> can be null) Return: concatenated string, or null on error

Notes: (1) This is a safe version of strcat; it makes a new string. (2) It is not an error if either or both of the strings are empty, or if either or both of the pointers are null.

Definition at line 934 of file utils.c.

References CALLOC, ERROR_PTR, NULL, PROCNAME, and stringCopy().

Referenced by captureProtoSignature(), genTempFilename(), main(), parseForProtos(), pixAddText(), pixHtmlViewer(), pixPlotAlongPta(), regTestCleanup(), and splitPathAtExtension().

char* stringReverse ( const char *  src)

stringReverse()

Input: src (string) Return: dest (newly-allocated reversed string)

Definition at line 964 of file utils.c.

References CALLOC, ERROR_PTR, NULL, and PROCNAME.

Referenced by barcodeDecode2of5(), barcodeDecode39(), barcodeDecode93(), barcodeDecodeCodabar(), barcodeDecodeEan13(), barcodeDecodeI2of5(), barcodeDecodeUpca(), and barcodeVerifyFormat().

char* strtokSafe ( char *  cstr,
const char *  seps,
char **  psaveptr 
)

strtokSafe()

Input: cstr (input string to be sequentially parsed; use NULL after the first call) seps (a string of character separators) &saveptr (<return> ptr to the next char after the last encountered separator) Return: substr (a new string that is copied from the previous saveptr up to but not including the next separator character), or NULL if end of cstr.

Notes: (1) This is a thread-safe implementation of strtok. (2) It has the same interface as strtok_r. (3) It differs from strtok_r in usage in two respects: (a) the input string is not altered (b) each returned substring is newly allocated and must be freed after use. (4) Let me repeat that. This is "safe" because the input string is not altered and because each returned string is newly allocated on the heap. (5) It is here because, surprisingly, some C libraries don't include strtok_r. (6) Important usage points:

  • Input the string to be parsed on the first invocation.
  • Then input NULL after that; the value returned in saveptr is used in all subsequent calls. (7) This is only slightly slower than strtok_k.

Definition at line 1014 of file utils.c.

References CALLOC, ERROR_PTR, NULL, PROCNAME, and stringCopy().

Referenced by getImagelibVersions(), parseStringForNumbers(), sarraySplitString(), and stringSplitOnToken().

l_int32 stringSplitOnToken ( char *  cstr,
const char *  seps,
char **  phead,
char **  ptail 
)

stringSplitOnToken()

Input: cstr (input string to be split; not altered) seps (a string of character separators) &head (<return> ptr to copy of the input string, up to the first separator token encountered) &tail (<return> ptr to copy of the part of the input string starting with the first non-separator character that occurs after the first separator is found) Return: 0 if OK, 1 on error

Notes: (1) The input string is not altered; all split parts are new strings. (2) The split occurs around the first consecutive sequence of tokens encountered. (3) The head goes from the beginning of the string up to but not including the first token found. (4) The tail contains the second part of the string, starting with the first char in that part that is NOT a token. (5) If no separator token is found, 'head' contains a copy of the input string and 'tail' is null.

Definition at line 1104 of file utils.c.

References ERROR_INT, NULL, PROCNAME, stringNew(), and strtokSafe().

char* stringRemoveChars ( const char *  src,
const char *  remchars 
)

stringRemoveChars()

Input: src (input string; can be of zero length) remchars (string of chars to be removed from src) Return: dest (string with specified chars removed), or null on error

Definition at line 1141 of file utils.c.

References CALLOC, ERROR_PTR, NULL, PROCNAME, and stringNew().

Referenced by morphSequenceVerify(), pixColorMorphSequence(), pixGrayMorphSequence(), pixMorphCompSequence(), pixMorphCompSequenceDwa(), pixMorphSequence(), and pixMorphSequenceDwa().

l_int32 stringFindSubstr ( const char *  src,
const char *  sub,
l_int32 ploc 
)

stringFindSubstr()

Input: src (input string; can be of zero length) sub (substring to be searched for) &loc (<return optional>=""> location of substring in src) Return: 1 if found; 0 if not found or on error

Notes: (1) This is a wrapper around strstr(). (2) Both and must be defined, and must have length of at least 1. (3) If the substring is not found and loc is returned, it has the value -1.

Definition at line 1184 of file utils.c.

References ERROR_INT, NULL, and PROCNAME.

Referenced by genPathname(), genTempFilename(), getRootNameFromArgv0(), and lept_fopen().

char* stringReplaceSubstr ( const char *  src,
const char *  sub1,
const char *  sub2,
l_int32 pfound,
l_int32 ploc 
)

stringReplaceSubstr()

Input: src (input string; can be of zero length) sub1 (substring to be replaced) sub2 (substring to put in; can be "") &found (<return optional>=""> 1 if sub1 is found; 0 otherwise) &loc (<return optional>=""> location of ptr after replacement) Return: dest (string with substring replaced), or null if the substring not found or on error.

Notes: (1) Replaces the first instance. (2) To only remove sub1, use "" for sub2 (3) Returns a new string if sub1 and sub2 are the same. (4) The optional loc is input as the byte offset within the src from which the search starts, and after the search it is the char position in the string of the next character after the substituted string. (5) N.B. If ploc is not null, loc must always be initialized. To search the string from the beginning, set loc = 0.

Definition at line 1234 of file utils.c.

References CALLOC, ERROR_PTR, NULL, and PROCNAME.

Referenced by stringReplaceEachSubstr().

char* stringReplaceEachSubstr ( const char *  src,
const char *  sub1,
const char *  sub2,
l_int32 pcount 
)

stringReplaceEachSubstr()

Input: src (input string; can be of zero length) sub1 (substring to be replaced) sub2 (substring to put in; can be "") &count (<optional return=""> the number of times that sub1 is found in src; 0 if not found) Return: dest (string with substring replaced), or null if the substring not found or on error.

Notes: (1) Replaces every instance. (2) To only remove each instance of sub1, use "" for sub2 (3) Returns NULL if sub1 and sub2 are the same.

Definition at line 1298 of file utils.c.

References ERROR_PTR, FREE, NULL, PROCNAME, and stringReplaceSubstr().

Referenced by genPathname().

NUMA* arrayFindEachSequence ( const l_uint8 data,
l_int32  datalen,
const l_uint8 sequence,
l_int32  seqlen 
)

arrayFindEachSequence()

Input: data (byte array) datalen (length of data, in bytes) sequence (subarray of bytes to find in data) seqlen (length of sequence, in bytes) Return: numa of offsets where the sequence is found, or null if none are found or on error

Notes: (1) The byte arrays and are not C strings, as they can contain null bytes. Therefore, for each we must give the length of the array. (2) This finds every occurrence in of .

Definition at line 1352 of file utils.c.

References arrayFindSequence(), ERROR_PTR, NULL, numaAddNumber(), numaCreate(), numaDestroy(), numaGetCount(), L_Memstream::offset, PROCNAME, and TRUE.

Referenced by l_byteaFindEachSequence(), and substituteObjectNumbers().

l_int32 arrayFindSequence ( const l_uint8 data,
l_int32  datalen,
const l_uint8 sequence,
l_int32  seqlen,
l_int32 poffset,
l_int32 pfound 
)

arrayFindSequence()

Input: data (byte array) datalen (length of data, in bytes) sequence (subarray of bytes to find in data) seqlen (length of sequence, in bytes) &offset (return> offset from beginning of data where the sequence begins) &found (<optional return>=""> 1 if sequence is found; 0 otherwise) Return: 0 if OK, 1 on error

Notes: (1) The byte arrays 'data' and 'sequence' are not C strings, as they can contain null bytes. Therefore, for each we must give the length of the array. (2) This searches for the first occurrence in of , which consists of bytes. The parameter must not exceed the actual length of the byte array. (3) If the sequence is not found, the offset will be set to -1.

Definition at line 1409 of file utils.c.

References ERROR_INT, and PROCNAME.

Referenced by arrayFindEachSequence(), parseTrailerPdf(), sarrayParseRange(), sarraySelectBySubstring(), and substituteObjectNumbers().

void* reallocNew ( void **  pindata,
l_int32  oldsize,
l_int32  newsize 
)

reallocNew()

Input: &indata (<optional>; nulls indata) size of input data to be copied (bytes) size of data to be reallocated (bytes) Return: ptr to new data, or null on error

Action: !N.B. (3) and (4)! (1) Allocates memory, initialized to 0 (2) Copies as much of the input data as possible to the new block, truncating the copy if necessary (3) Frees the input data (4) Zeroes the input data ptr

Notes: (1) If newsize <=0, just frees input data and nulls ptr (2) If input ptr is null, just callocs new memory (3) This differs from realloc in that it always allocates new memory (if newsize > 0) and initializes it to 0, it requires the amount of old data to be copied, and it takes the address of the input ptr and nulls the handle.

Definition at line 1477 of file utils.c.

References CALLOC, ERROR_PTR, FREE, L_MIN, NULL, and PROCNAME.

Referenced by bbufferExtendArray(), boxaaExtendArray(), boxaExtendArrayToSize(), ccbaExtendArray(), fpixaExtendArrayToSize(), l_byteaExtendArrayToSize(), lheapExtendArray(), lqueueExtendArray(), lstackExtendArray(), numaaExtendArray(), numaExtendArray(), numaSetCount(), pixaaExtendArray(), pixacompExtendArray(), pixaExtendArrayToSize(), ptaaExtendArray(), ptaExtendArrays(), ptraExtendArray(), sarrayExtendArray(), selaExtendArray(), and tiffWriteCallback().

l_uint8* l_binaryReadStream ( FILE *  fp,
size_t *  pnbytes 
)

l_binaryReadStream()

Input: stream &nbytes (<return> number of bytes read) Return: null-terminated array, or null on error (reading 0 bytes is not an error)

Notes: (1) The returned array is terminated with a null byte so that it can be used to read ascii data into a proper C string. (2) Side effect: this re-positions the stream ptr to the beginning of the file.

Definition at line 1569 of file utils.c.

References CALLOC, ERROR_PTR, fnbytesInFile(), NULL, and PROCNAME.

Referenced by ccbaReadStream(), l_binaryRead(), l_byteaInitFromStream(), pixReadStreamSpix(), and pixReadStreamWebP().

l_int32 l_binaryWrite ( const char *  filename,
const char *  operation,
void *  data,
size_t  nbytes 
)
size_t nbytesInFile ( const char *  filename)

nbytesInFile()

Input: filename Return: nbytes in file; 0 on error

Definition at line 1643 of file utils.c.

References ERROR_INT, fnbytesInFile(), fopenReadStream(), NULL, and PROCNAME.

Referenced by filesAreIdentical(), get_header_data(), and main().

size_t fnbytesInFile ( FILE *  fp)

fnbytesInFile()

Input: file stream Return: nbytes in file; 0 on error

Definition at line 1667 of file utils.c.

References ERROR_INT, and PROCNAME.

Referenced by arrayReadStream(), findFileFormatStream(), freadHeaderPng(), freadHeaderSpix(), l_binaryReadStream(), and nbytesInFile().

l_uint8* l_binaryCopy ( l_uint8 datas,
size_t  size 
)

l_binaryCopy()

Input: datas size (of data array) Return: datad (on heap), or null on error

Notes: (1) We add 4 bytes to the zeroed output because in some cases (e.g., string handling) it is important to have the data be null terminated. This guarantees that after the memcpy, the result is automatically null terminated.

Definition at line 1701 of file utils.c.

References CALLOC, ERROR_PTR, NULL, and PROCNAME.

Referenced by l_byteaCopyData(), and pixcompCreateFromString().

l_int32 fileCopy ( const char *  srcfile,
const char *  newfile 
)

fileCopy()

Input: srcfile (copy this file) newfile (to this file) Return: 0 if OK, 1 on error

Definition at line 1729 of file utils.c.

References ERROR_INT, FREE, l_binaryRead(), l_binaryWrite(), NULL, and PROCNAME.

Referenced by regTestCheckFile().

l_int32 fileConcatenate ( const char *  srcfile,
const char *  destfile 
)

fileConcatenate()

Input: srcfile (file to append) destfile (file to add to) Return: 0 if OK, 1 on error

Definition at line 1759 of file utils.c.

References ERROR_INT, FREE, l_binaryRead(), l_binaryWrite(), and PROCNAME.

l_int32 fileAppendString ( const char *  filename,
const char *  str 
)

fileAppendString()

Input: filename str (string to append to file) Return: 0 if OK, 1 on error

Definition at line 1787 of file utils.c.

References ERROR_INT, fopenWriteStream(), NULL, and PROCNAME.

Referenced by regTestCleanup().

l_int32 filesAreIdentical ( const char *  fname1,
const char *  fname2,
l_int32 psame 
)

filesAreIdentical()

Input: fname1 fname2 &same (<return> 1 if identical; 0 if different) Return: 0 if OK, 1 on error

Definition at line 1819 of file utils.c.

References ERROR_INT, FREE, l_binaryRead(), nbytesInFile(), NULL, and PROCNAME.

Referenced by main(), regTestCheckFile(), and regTestCompareFiles().

l_uint16 convertOnLittleEnd16 ( l_uint16  shortin)

Definition at line 1887 of file utils.c.

Referenced by sreadHeaderPng().

l_uint16 convertOnBigEnd16 ( l_uint16  shortin)

Definition at line 1893 of file utils.c.

Referenced by findFileFormatBuffer(), pixReadStreamBmp(), and pixWriteStreamBmp().

l_uint32 convertOnLittleEnd32 ( l_uint32  wordin)

Definition at line 1922 of file utils.c.

Referenced by sreadHeaderPng().

l_uint32 convertOnBigEnd32 ( l_uint32  wordin)

Definition at line 1929 of file utils.c.

Referenced by pixReadStreamBmp(), and pixWriteStreamBmp().

FILE* fopenWriteStream ( const char *  filename,
const char *  modestring 
)

fopenWriteStream()

Input: filename modestring Return: stream, or null on error

Notes: (1) This wrapper also handles pathname conversions for Windows. It should be used whenever you want to run fopen() to write or append to a stream.

Definition at line 1993 of file utils.c.

References ERROR_PTR, FREE, genPathname(), NULL, and PROCNAME.

Referenced by boxaaWrite(), boxaWrite(), ccbaWrite(), dewarpWrite(), dpixWrite(), fileAppendString(), fpixWrite(), gplotGenCommandFile(), gplotGenDataFiles(), gplotWrite(), jbDataWrite(), kernelWrite(), l_binaryWrite(), l_byteaWrite(), lept_fopen(), numaaWrite(), numaWrite(), pixacompWrite(), pixWriteJpeg(), pixWritePng(), pixWritePSEmbed(), pixWriteWebP(), pixWriteWebPwithTargetPSNR(), pmsGetAlloc(), ptaaWrite(), ptaWrite(), regTestSetup(), sarrayAppend(), sarrayWrite(), selaWrite(), and selWrite().

FILE* lept_fopen ( const char *  filename,
const char *  mode 
)

lept_fopen()

Input: filename mode (same as for fopen(); e.g., "rb") Return: stream or null on error

Notes: (1) This must be used by any application that passes a file handle to a leptonica Windows DLL.

Definition at line 2041 of file utils.c.

References ERROR_PTR, fopenReadStream(), fopenWriteStream(), NULL, PROCNAME, and stringFindSubstr().

Referenced by main(), and testcomp().

l_int32 lept_fclose ( FILE *  fp)

lept_fclose()

Input: fp (stream handle) Return: 0 if OK, 1 on error

Notes: (1) This should be used by any application that accepts a file handle generated by a leptonica Windows DLL.

Definition at line 2069 of file utils.c.

References ERROR_INT, and PROCNAME.

Referenced by main(), and testcomp().

void* lept_calloc ( size_t  nmemb,
size_t  size 
)

lept_calloc()

Input: nmemb (number of members) size (of each member) Return: void ptr, or null on error

Notes: (1) For safety with windows DLLs, this can be used in conjunction with lept_free() to avoid C-runtime boundary problems. Just use these two functions throughout your application.

Definition at line 2093 of file utils.c.

References CALLOC, and NULL.

Referenced by main().

void lept_free ( void *  ptr)

lept_free()

Input: void ptr Return: 0 if OK, 1 on error

Notes: (1) This should be used by any application that accepts heap data allocated by a leptonica Windows DLL.

Definition at line 2113 of file utils.c.

References FREE.

Referenced by get_header_data(), main(), test_mem_gif(), test_mem_png(), and test_writemem().

l_int32 lept_mkdir ( const char *  subdir)

lept_mkdir()

Input: subdir Return: 0 on success, non-zero on failure

Notes: (1) This makes a subdirectory of /tmp/. (2) Use unix pathname separators. (3) On Windows, it makes a subdirectory of <Temp>/leptonica, where <Temp> is the Windows temp dir. The name translation is: /tmp --> <Temp>/leptonica

Definition at line 2139 of file utils.c.

References ERROR_INT, FREE, genPathname(), NULL, pathJoin(), and PROCNAME.

Referenced by main(), pixDisplayWithTitle(), and regTestSetup().

l_int32 lept_rmdir ( const char *  subdir)

lept_rmdir()

Input: subdir (of /tmp or its equivalent on Windows) Return: 0 on success, non-zero on failure

Notes: (1) On unix, this removes all the files in the named subdirectory of /tmp. It then removes the subdirectory. (2) Use unix pathname separators. (3) On Windows, the affected directory is a subdirectory of <Temp>/leptonica, where <Temp> is the Windows temp dir. (4) TODO: Use a new function lept_dirExists(path) to test if the directory exists, and if not, fail silently.

Definition at line 2194 of file utils.c.

References ERROR_INT, FREE, genPathname(), getFilenamesInDirectory(), L_NOCOPY, L_WARNING_STRING, nfiles, NULL, pathJoin(), PROCNAME, sarrayDestroy(), sarrayGetCount(), and sarrayGetString().

Referenced by main(), and pixDisplayWithTitle().

l_int32 lept_rm ( const char *  subdir,
const char *  filename 
)

lept_rm()

Input: subdir (can be NULL, in which case the removed file is in /tmp) filename (without the directory) Return: 0 on success, non-zero on failure

Notes: (1) This removes the named file in /tmp or a subdirectory of /tmp. If the file is in /tmp, use NULL for the subdir. (2) Use unix pathname separators. (3) On Windows, the file is in either <Temp>/leptonica, or a subdirectory of this, where <Temp> is the Windows temp dir. The name translation is: /tmp --> <Temp>/leptonica

Definition at line 2264 of file utils.c.

References ERROR_INT, FREE, genPathname(), NULL, pathJoin(), and PROCNAME.

Referenced by main().

l_int32 lept_mv ( const char *  srcfile,
const char *  newfile 
)

lept_mv()

Input: srcfile, newfile Return: 0 on success, non-zero on failure

Notes: (1) This moves a srcfile to /tmp or to a subdirectory of /tmp. (2) The input srcfile name is the complete pathname. The input newfile is either in /tmp or a subdirectory of /tmp, and newfile can be specified either as the full path or without the leading '/tmp'. (3) Use unix pathname separators. (4) On Windows, the source and target filename are altered internally if necessary to conform to the Windows temp file. The name translation is: /tmp --> <Temp>/leptonica

Definition at line 2325 of file utils.c.

References CALLOC, ERROR_INT, FREE, genPathname(), NULL, pathJoin(), PROCNAME, splitPathAtDirectory(), and stringNew().

Referenced by main().

l_int32 lept_cp ( const char *  srcfile,
const char *  newfile 
)

lept_cp()

Input: srcfile newfile Return: 0 on success, non-zero on failure

Notes: (1) This copies a file to /tmp or a subdirectory of /tmp. (2) The input srcfile name is the complete pathname. The input newfile is either in /tmp or a subdirectory of /tmp, and newfile can be specified either as the full path or without the leading '/tmp'. (3) Use unix pathname separators. (4) On Windows, the source and target filename are altered internally if necessary to conform to the Windows temp file. (5) Alternatively, you can use fileCopy(). This avoids forking a new process and has no restrictions on the destination directory.

Definition at line 2404 of file utils.c.

References CALLOC, ERROR_INT, FALSE, FREE, genPathname(), NULL, pathJoin(), PROCNAME, splitPathAtDirectory(), and stringNew().

Referenced by main().

l_int32 splitPathAtDirectory ( const char *  pathname,
char **  pdir,
char **  ptail 
)

splitPathAtDirectory()

Input: pathname (full path; can be a directory) &dir (<optional return>=""> root directory name of input path, including trailing '/') &tail (<optional return>=""> path tail, which is either the file name within the root directory or the last sub-directory in the path) Return: 0 if OK, 1 on error

Notes: (1) If you only want the tail, input null for the root directory ptr. (2) If you only want the root directory name, input null for the tail ptr. (3) This function makes decisions based only on the lexical structure of the input. Examples: /usr/tmp/abc --> dir: /usr/tmp/ tail: abc /usr/tmp/ --> dir: /usr/tmp/ tail: [empty string] /usr/tmp --> dir: /usr/ tail: tmp (4) N.B. The input pathname must have unix directory separators for unix and windows directory separators for windows.

Definition at line 2487 of file utils.c.

References ERROR_INT, FREE, NULL, PROCNAME, sepchar, and stringNew().

Referenced by convertFilesTo1bpp(), extractNumberFromFilename(), fopenReadStream(), getRootNameFromArgv0(), lept_cp(), lept_mv(), main(), pixDisplayMultiple(), selReadFromColorImage(), and splitPathAtExtension().

l_int32 splitPathAtExtension ( const char *  pathname,
char **  pbasename,
char **  pextension 
)

splitPathAtExtension()

Input: pathname (full path; can be a directory) &basename (<optional return>=""> pathname not including the last dot and characters after that) &extension (<optional return>=""> path extension, which is the last dot and the characters after it. If there is no extension, it returns the empty string) Return: 0 if OK, 1 on error

Notes: (1) If you only want the extension, input null for the basename ptr. (2) If you only want the basename without extension, input null for the extension ptr. (3) This function makes decisions based only on the lexical structure of the input. Examples: /usr/tmp/abc.jpg --> basename: /usr/tmp/abc ext: .jpg /usr/tmp/.jpg --> basename: /usr/tmp/ tail: .jpg /usr/tmp.jpg/ --> basename: /usr/tmp.jpg/ tail: [empty str] ./.jpg --> basename: ./ tail: .jpg (4) N.B. The input pathname must have unix directory separators for unix and windows directory separators for windows.

Definition at line 2551 of file utils.c.

References ERROR_INT, FREE, NULL, PROCNAME, splitPathAtDirectory(), stringJoin(), and stringNew().

Referenced by convertFilesTo1bpp(), extractNumberFromFilename(), getImpliedFileFormat(), main(), pixWrite(), regTestCheckFile(), and selReadFromColorImage().

char* pathJoin ( const char *  dir,
const char *  fname 
)
l_int32 extractNumberFromFilename ( const char *  fname,
l_int32  numpre,
l_int32  numpost 
)

extractNumberFromFilename()

Input: fname numpre (number of characters before the digits to be found) numpost (number of characters after the digits to be found) Return: num (number embedded in the filename); -1 on error or if not found

Notes: (1) Use unix-style pathname separators ('/'). (2) The number is to be found in the basename, which is the filename without either the directory or the last extension. (3) When a number is found, it is non-negative. If no number is found, this returns -1, without an error message. The caller needs to check.

Definition at line 2907 of file utils.c.

References ERROR_INT, FREE, NULL, PROCNAME, splitPathAtDirectory(), and splitPathAtExtension().

Referenced by getNumberedPathnamesInDirectory().

l_int32 genRandomIntegerInRange ( l_int32  range,
l_int32  seed,
l_int32 pval 
)

genRandomIntegerInRange()

Input: range (size of range; must be >= 2) seed (use 0 to skip; otherwise call srand) val (<return> random integer in range {0 ... range-1} Return: 0 if OK, 1 on error

Notes: (1) For example, to choose a rand integer between 0 and 99, use = 100.

Definition at line 2956 of file utils.c.

References ERROR_INT, and PROCNAME.

Referenced by sudokuGenerate().

char* getLeptonicaVersion ( )

getLeptonicaVersion()

Return: string of version number (e.g., 'leptonica-1.68')

Notes: (1) The caller has responsibility to free the memory.

Definition at line 2987 of file utils.c.

References CALLOC, LIBLEPT_MAJOR_VERSION, LIBLEPT_MINOR_VERSION, and version.

Referenced by generateFixedStringsPdf(), main(), and regTestSetup().

void startTimer ( void  )

startTimer(), stopTimer()

Example of usage:

startTimer(); .... fprintf(stderr, "Elapsed time = %7.3f sec\n", stopTimer());

Definition at line 3044 of file utils.c.

References rusage_before.

Referenced by BoxaSortTest(), DoComparisonDwa1(), DoComparisonDwa2(), DoComparisonDwa3(), DoComparisonDwa4(), DoComparisonDwa5(), GeneratePattern(), main(), PixaSortTest(), PixTest1(), and PixTest2().

L_TIMER startTimerNested ( void  )

startTimerNested(), stopTimerNested()

Example of usage:

L_TIMER t1 = startTimerNested(); .... L_TIMER t2 = startTimerNested(); .... fprintf(stderr, "Elapsed time 2 = %7.3f sec\n", stopTimerNested(t2)); .... fprintf(stderr, "Elapsed time 1 = %7.3f sec\n", stopTimerNested(t1));

Definition at line 3076 of file utils.c.

References CALLOC.

Referenced by regTestSetup().

l_float32 stopTimerNested ( L_TIMER  rusage_start)

Definition at line 3086 of file utils.c.

References FREE.

Referenced by regTestCleanup().

void l_getCurrentTime ( l_int32 sec,
l_int32 usec 
)

l_getCurrentTime()

Input: &sec (<optional return>=""> in seconds since birth of Unix) &usec (<optional return>=""> in microseconds since birth of Unix) Return: void

Definition at line 3110 of file utils.c.

References NULL.

Referenced by genTempFilename(), and main().

char* l_getFormattedDate ( )

l_getFormattedDate()

Input: (none) Return: formatted date string, or null on error

Definition at line 3231 of file utils.c.

References buf, NULL, and stringNew().

Referenced by generateFixedStringsPdf().

l_uint8* arrayRead ( const char *  fname,
l_int32 pnbytes 
)

arrayRead()

Input: filename &nbytes (<return> number of bytes read) Return: array, or null on error

Definition at line 3256 of file utils.c.

References arrayReadStream(), ERROR_PTR, fopenReadStream(), NULL, and PROCNAME.

l_uint8* arrayReadStream ( FILE *  fp,
l_int32 pnbytes 
)

arrayReadStream()

Input: stream &nbytes (<return> number of bytes read) Return: null-terminated array, or null on error (reading 0 bytes is not an error)

Notes: (1) N.B.: as a side effect, this always re-positions the stream ptr to the beginning of the file.

Definition at line 3293 of file utils.c.

References CALLOC, ERROR_PTR, fnbytesInFile(), NULL, and PROCNAME.

Referenced by arrayRead().


Variable Documentation

const char sepchar = '/' [static]

Definition at line 161 of file utils.c.

Referenced by genPathname(), and splitPathAtDirectory().

struct rusage rusage_before [static]

Definition at line 3031 of file utils.c.

Referenced by startTimer(), and stopTimer().

struct rusage rusage_after [static]

Definition at line 3032 of file utils.c.

Referenced by stopTimer().

 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Defines