in Programming in C reopened by
1,202 views
1 vote
1 vote

I'm trying to use the fseek() and ftell() function to find the length of the file 'test.txt' which is present in the same directory as the file 'file.c'.


file.c

#include <stdio.h>

int main()
{
    FILE *fp;
    int len;
    fp = fopen("test.txt", "r");

    if(fp == NULL)
    printf("Error opening file.");

    fseek(fp, 0, SEEK_END);
    len = ftell(fp);
    fclose(fp);
    printf("The size of the file test.txt is: %d.\n", len);

    return 0;  
}


test.txt

abc def


There is no problem when I compile the file, but when I try to run it, I'm getting the 'Segmentation fault (core dumped)' error abd the execution terminates.

What's going wrong in here?

in Programming in C reopened by
by
1.2k views

3 Comments

Code is correct. Are you using some virtual machine? You can do gdb ./a.out and then type run. See what error you get.
0
0

@Arjun

I am not using a virtual machine, though I am not logged on to a super user.

Actually I had not put a newline character \n after the error message here

 if(fp == NULL)
    printf("Error opening file.");

So I was not getting this message because of stream buffering of stdiout.

For some reason the file was not being accessible which got resolved when I created a new file instead of test.txt.

0
0
should I study file handling for GATE CSE 2022?
0
0

1 Answer

0 votes
0 votes

Nice thanks

Shoviv

Related questions