For streams, this works, for devices requiring a file handle, lseek() should work, but it won't work on terminals and printers, according to my help file.
Code:
/*
fseek Repositions the file pointer of a stream.
Syntax:
int fseek(FILE *stream, long offset, int whence);
Prototype in:
stdio.h
Remarks:
fseek sets the file pointer associated with stream to a new position
that is offset bytes from the file location given by whence.
For text mode streams, offset should be 0 or a value returned by
ftell.
whence must be one of the values 0, 1, or 2, which represent three
symbolic constants (defined in stdio.h) as follows:
whence ³ File location
======================================
SEEK_SET (0) ³ File beginning
SEEK_CUR (1) ³ Current file pointer position
SEEK_END (2) ³ End-of-file
fseek discards any character pushed back using ungetc.
fseek is used with stream I/O. For file handle I/O, use lseek.
After fseek, the next operation on an update file can be either input
or output.
Return Value:
fseek returns 0 if the pointer is successfully moved. It returns a
nonzero on failure.
fseek can return a zero, indicating that the pointer has been moved
successfully, when in fact it has not been. This is because DOS,
which actually resets the pointer, does not verify the setting.
fseek returns an error code only on an unopened file or device.
Portability:
fseek is available on all UNIX systems and is defined in ANSI C.
See Also:
fgetpos fsetpos lseek setbuf
fopen ftell rewind tell
Example:
*/
#include <stdio.h>
long filesize(FILE *stream);
int main(void)
{
FILE *stream;
stream = fopen("MYFILE.TXT", "w+");
fprintf(stream, "This is a test");
printf("Filesize of MYFILE.TXT is %ld bytes\n", filesize(stream));
fclose(stream);
return 0;
}
long filesize(FILE *stream)
{
long curpos, length;
curpos = ftell(stream);
fseek(stream, 0L, SEEK_END);
length = ftell(stream);
fseek(stream, curpos, SEEK_SET);
return length;
}