-
File I/O
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.
-
Pass the file pointer to the function if you want to keep using the file pointer after the function has finished, like this (may not compile I only quickly cut and pasted it together):
Code:
#include <stdio.h>
#define NUM_LOOPS 8
#define BLOCK_SIZE 2
void access_file(FILE *fp);
int main(void)
{
int i;
FILE *fp = fopen("input.txt", "r");
if(fp == NULL)
{
printf("Error: Cannot open file input.txt!\n");
return 0;
}
for (i = 0; i<NUM_LOOPS; i++)
{
access_file(fp);
}
fclose(fp);
return 0;
}
void access_file(FILE *fp)
{
int i, array[BLOCK_SIZE];
for (i = 0; i<BLOCK_SIZE; i++)
{
fscanf(fp, "%d", &array[i]);
}
}
also don't use void main
-
first off, read this :]
besides that.. your missing a quotation mark on line 26 and your not opening the file correctly. it could be
Code:
FILE *fp = fopen("input.txt", "r");
then when your trying to access input with fseek and fscan, your using an undeclared variable. since you opened the file w/the variable "fp", you should be using that instead of this variable "input" which it seems you've just made up. lol
thats all for now, its time to open presents.