Hello: The 'Net has helped me so much, time to try and return the favor.
I had spent many hours debugging a file reading program that was generating segmentation fault aborts. With debugging tools I narrowed it down to an apparent conflict between malloc'ed memory and fclose(). ('Net Research on this set of circumstances even produced reports of the problem being absent on *NIX systems, but present on Linux).
There comes a time when you cut your losses and try a different approach. While perhaps not the optimum, the example below shows what changes I made to the existing code (now commented out).
The basis of the change is to replace fopen, fread/getc, fclose with open, read, close (lower-level calls).
If the reader needs more back-story on this program - including more info on variables not seen defined in this snippet - feel free to contact.
FWIW, the program being created is intended to take .eml, .msg and .txt (which contain the .eml format) files, extract certain header lines ("To:, From:, Subject:, Date:, Cc, for importing into a MySQL database. The end result hopes to be an archive of email files sortable on the headers. The entirety of the email file is also loaded into the DB. This way, many thousands of emails can be hard-archived to .7z or .rar or .zip, the the emails in the DB can be searched if needed.
Best, GnS.
Code:
int blockread()
{
int fhandle;
/* int inint; */
int close_ret;
int retval;
int getmem_flag;
long n;
long *bufptr;
/* FILE *lfp; */
getmem_flag = OK;
errno = 0;
retval = OK;
/* if ((lfp = fopen(pd.tmp, "rb")) != (FILE *) NULL) */
fhandle = open(pd.tmp, O_RDONLY);
if (fhandle != -1) /* error condition for open() */
{
pd.wholefile = (long *) xmalloc(&getmem_flag);
bufptr = pd.wholefile;
if (getmem_flag != OK)
{
/* fclose(lfp); */
close_ret = close(fhandle);
if (close_ret != 0)
fprintf(pd.log_fp, "\nclose() input file returned %d, %s.\n", close_ret, strerror(errno));
fprintf(pd.log_fp, "\nAborting read file %s.\n", pd.tmp);
return(BAD);
}
/* for (n = 0l; (inint = getc(lfp)) != EOF && n < pd.cur_fsize; n++)
*bufptr++ = inint; */
n = read(fhandle, bufptr, pd.cur_fsize);
/* fclose(lfp); */
close_ret = close(fhandle);
if (close_ret != 0)
fprintf(pd.log_fp, "\nclose() input file returned %d, %s.\n", close_ret, strerror(errno));
/* if (n != pd.cur_fsize) */
if ((n != pd.cur_fsize) || (errno != 0))
{
fprintf(pd.log_fp, "\nRead %s problem, expected %ld, got %ld bytes\n", pd.tmp, pd.cur_fsize, n);
return(BAD);
}
}
else
fprintf(pd.log_fp, "\nFail open %s, %s\n", pd.tmp, strerror(errno));
return(retval);
}