Hi All,
I've got another sanity-questioning problem to pose for you. I am trying to read the contents of a file, but I'm only able to read a small fraction of the file (15232 / 2912998 Bytes). gfc->mfbuf_p is a file pointer that was just recently writing to this same file. To be safe, I close this file and reopen it for reading only with a new file pointer. The code is given below.
Code:
void func(...) {
FILE *fp;
int sz;
struct flags *gfc;
sample_t mfbuf[2][MFSIZE]; // MFSIZE is 3984
...
// Open the temporary file for storing sampled data...
gfc->mfbuf_p = fopen(TEMP_FILE, "w+");
if(gfc->mfbuf_p == NULL) {
printf("Could not open temporary file!\n");
exit(1);
}
...
// Fill up a large mfbuf
sz = fwrite((void*) mfbuf[0], sizeof(sample_t), mf_needed, gfc->mfbuf_p);
sz += fwrite((void*) mfbuf[1], sizeof(sample_t), mf_needed, gfc->mfbuf_p);
if (sz != 2*mf_needed) {
printf("FWRITE failed! Only %d bytes were written, not %d bytes", sz, 2*mf_needed);
exit(1);
}
...
// Read saved samples from file and encode them...
// Had some problems reading.. let's close and reopen
if(fflush(gfc->mfbuf_p) != 0) {
perror("FFLUSH failed!");
exit(1);
}
if (fclose(gfc->mfbuf_p) != 0) {
perror("Closing failed!");
exit(1);
}
fp = fopen(TEMP_FILE, "r");
if (fp == NULL) {
perror("Unable to open tmp file for reading!\n");
exit(1);
}
while (!feof(fp)) {
int mf_needed, sz;
long off;
off = ftell(fp);
printf("\n\nOFfset: %ld\n", off);
mf_needed = 1904;
sz = fread((void*) &mfbuf[0][0], sizeof(sample_t), mf_needed, fp);
off = ftell(fp);
printf("\n\nOFfset: %ld\n", off);
if(sz != mf_needed && !feof(fp)) {
perror("\n\nFAILED to read from temp file ONE!\n\n");
exit(1);
}
sz += fread((void*) &mfbuf[1][0], sizeof(sample_t), mf_needed, fp);
if(sz != 2*mf_needed && !feof(fp)) {
perror("\n\nFAILED to read from temp file!\n\n");
exit(1);
}
}
}
This seems to work the first iteration, but fails the second iteration. It says it reads 1377 Bytes (out of the 1904 it should have read), and errno indicates an invalid argument. As I step through, I can see that the file pointer itself still points to a valid FILE structure, though after the failing read, I suspect some of its internal pointers may be corrupt (but I have no way of knowing).
Any ideas?