Hi,
I am trying to write a function that is called from within a loop
in main(). Each time the function is called it reads a block of integer values into an array, and remembers the location of the file pointer so that the next function call continues to read data from the last file exit position. I have tried using 'fseek()' and
a static variable as shown below. This program should call the
function 'access_file()' 8 times. During each call, 'access_file()'
reads 2 integer values into an array, and keeps a record of the
last file position so that the next calls to 'access_file()' perform
a sequential read of 16 (2x8) different values from the file 'input.txt'.
Code:
#include <stdio.h>
#define NUM_LOOPS 8
#define BLOCK_SIZE 2
void access_file(void);
void main()
{
int i;
for (i = 0; i<NUM_LOOPS; i++)
{
access_file();
}
}
void access_file()
{
int i, array[BLOCK_SIZE];
static long offset = 0;
FILE *fp = ("input.txt);
if(fp == NULL)
{
printf("Error: Cannot open file input.txt!\n");
}
for (i = 0; i<BLOCK_SIZE; i++)
{
fseek(input, (offset * sizeof(int)), SEEK_SET);
fscanf(input, "%d", &array[i]);
printf("offset = %ld, array_value = %d\n", offset, array[i]);
offset++;
}
fclose(input);
}
However, the end result varies depending on the contents of the
file. Some values are skipped or only 1 digit of a two digit value
is read. I have also tried using 'fgetpos()' and 'fsetpos()' with similar results.
Any ideas?
Thanks.
Mees
P.S an int on my compiler is 4 bytes long, and I suspect it has something to do with exceeded the byte-wide boundaries of variables but I can't explain how or why.