QUESTION 13
What is the purpose of ftell?
2 marksAnswer
It obtains a stream position indication as long, returning a negative value on failure. Text-stream values need not be simple byte offsets.
QUESTION 13
It obtains a stream position indication as long, returning a negative value on failure. Text-stream values need not be simple byte offsets.
QUESTION 14
Positioning functions allow a stream to revisit suitable locations instead of always reading sequentially.
The demonstration writes three ints, then uses a checked fseek with offset sizeof(int) from SEEK_SET. This selects the second native int record, which is read and displayed as 20. The offset is small and representable in long for this example.
Do not assume arbitrary byte arithmetic works on text positions. A portable text-stream seek uses permitted forms such as offset zero or a suitable earlier ftell value with SEEK_SET. For saved positions, fgetpos and fsetpos can preserve stream state represented by fpos_t.
fseek returns zero on success. A successful seek clears the EOF indicator. Positioning can also provide a required transition between reading and writing on an update stream. Do not use an unchecked failed seek and then claim a particular record was accessed.
The interface does not guarantee a universal O(1) physical-device seek. Direct fixed-record indexing avoids comparing every previous record, but filesystem and device costs remain implementation-dependent. Variable-length records require a separate way to discover their boundaries.
This demonstration creates or replaces its codebhavya_* sample file in the working directory. Run it in a separate test directory. Native binary examples use one compatible implementation.
/* CodeBhavya | Data Structures AR25 | Learning example */
#include <stdio.h>
int main(void)
{
int a[3] = {10, 20, 30}, value;
FILE *fp = fopen("codebhavya_position_demo.bin", "wb");
if (fp == NULL) { puts("Open failed"); return 1; }
if (fwrite(a, sizeof a[0], 3, fp) != 3) { fclose(fp); puts("Write failed"); return 1; }
if (fclose(fp) != 0) { puts("Close failed"); return 1; }
fp = fopen("codebhavya_position_demo.bin", "rb");
if (fp == NULL) { puts("Open failed"); return 1; }
if (fseek(fp, (long)sizeof(int), SEEK_SET) != 0 || fread(&value, sizeof value, 1, fp) != 1) {
fclose(fp); puts("Position/read failed"); return 1;
}
if (fclose(fp) != 0) { puts("Close failed"); return 1; }
printf("Second = %d\n", value);
return 0;
}The example uses values in the code.
Second = 20