Why do I need to matOpen() again after calling matGetDir()?

I am studying the example file matdgns.c provided by MATLAB. The file first calls matOpen() to open a MAT file.
pmat = matOpen(file, "r");
Second, it calls matGetDir() to get directory of the file:
dir = (const char **)matGetDir(pmat, &ndir);
Third, it calls matOpen() again before loading head information by the function of:
pa = matGetNextVariableInfo(pmat, &name);
I found errors if pmat is not re-opened after matGetDir(). The comment says: /* In order to use matGetNextXXX correctly, reopen file to read in headers. */
My question is why we have to open it again?
Thanks!
/*
* Open file to get directory
*/
pmat = matOpen(file, "r");
if (pmat == NULL) {
printf("Error opening file %s\n", file);
return(1);
}
/*
* get directory of MAT-file
*/
dir = (const char **)matGetDir(pmat, &ndir);
if (dir == NULL) {
printf("Error reading directory of file %s\n", file);
return(1);
} else {
printf("Directory of %s:\n", file);
for (i=0; i < ndir; i++)
printf("%s\n",dir[i]);
}
mxFree(dir);
/* In order to use matGetNextXXX correctly, reopen file to read in headers. */
if (matClose(pmat) != 0) {
printf("Error closing file %s\n",file);
return(1);
}
pmat = matOpen(file, "r");
if (pmat == NULL) {
printf("Error reopening file %s\n", file);
return(1);
}
/* Get headers of all variables */
printf("\nExamining the header for each variable:\n");
for (i=0; i < ndir; i++) {
pa = matGetNextVariableInfo(pmat, &name);
if (pa == NULL) {
printf("Error reading in file %s\n", file);
return(1);
}
/* Diagnose header pa */
printf("According to its header, array %s has %d dimensions\n",
name, mxGetNumberOfDimensions(pa));
if (mxIsFromGlobalWS(pa))
printf(" and was a global variable when saved\n");
else
printf(" and was a local variable when saved\n");
mxDestroyArray(pa);
}

Answers (1)

Geoff Hayes
Geoff Hayes on 5 Feb 2015
Edited: Geoff Hayes on 5 Feb 2015
Guanqun - given that matGetDir determines the list of variables in the mat file, it may be that the pmat pointer is no longer positioned at the beginning of the file and so needs to be reset to the beginning by closing the file and then re-opening it. This is kind of similar to using fopen with fread in that after every call to fread, the file pointer is and positioned after the last value read.

Tags

No tags entered yet.

Asked:

on 4 Feb 2015

Edited:

on 5 Feb 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!