Question

Can anyone please tell me what I'm doing wrong here with ftell?

I'm just messing around in C, and I've found that the following code sends me a terminal message of -1 meaning an error according to https://publib.boulder.ibm.com/infocenter/zos/v1r13/index.jsp?topic=%2Fcom.ibm.zos.r13.bpxbd00%2Fftell.htm, and crashes the program.

What am I doing incorrectly? Is it something to do with pointers?

Thanks

#include <stdio.h>
#include <string.h>

int main()
{
    FILE * f;
    char * s = "Hey Buddy!";
    f = fopen("myFile.txt", "w");

    int count = strlen(s);

    for (int i = 0; i < count; i++)
    {
        printf("%d\n", ftell(i));
        fputc(s[i], f);
    }

    fclose(f);
    return 0;
}

The program is supposed to iterate over 's' (printing it one letter at a time to f), while also printing into the terminal, how far along the array it has traversed. 0 = H, 1 = e, 2 = y, etc

Was it helpful?

Solution

You need to pass f as the argument to ftell, not i, since ftell expects a pointer to a FILE object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top