Search code examples
cfilesegmentation-faultasciifopen

C file to check if file is empty or contains ASCII text


I'm trying to write a program which should be able to take a file as input in terminal and then determine if the file is empty or written in ASCII text. But I keep getting segmentation fault 11.

My code is as follows:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    unsigned char c;
    int size;

    FILE *file = fopen(argv[1], "r");

    fseek(&c, 0, SEEK_END);
    size = ftell(file);

    if (size == 0)
    {
        printf("file is empty\n");
    }

    fclose(file);

    FILE *file = fopen(argv[1], "r");
    c = fgetc(file);

    if (c != EOF && c <= 127)
    {
        printf("ASCII\n");
    }

    fclose(file);
}

Any ideas as to why?


Solution

  • 1] fseek doesnt have first argument unsgined char*, but FILE*.

    fseek(file, 0, SEEK_END);

    2] You shouldn't use unsigned char / char for checking for EOF, use int for sure.

    3] Working and simplier code

    int main(int argc, char *argv[])
    {
        if (argc < 2)
        {
            // err we havent filename
            return 1;
        }
    
        int c;
    
        FILE *file = fopen(argv[1], "r");
        if (file == NULL)
        {
            // err failed to open file
            return 1;
        }
    
        c = fgetc(file);
    
        if (c == EOF)
        {
            printf("empty\n");
            fclose(file);
            return 0;
        }
        else
        {
            ungetc(c, file);
        }
    
        while ((c = fgetc(file)) != EOF)
        {
            if (c < 0 || c > 127)
            {
                // not ascii
                return 1;
            }
        }
    
        printf("ascii\n");
    
        fclose(file);
        return 0;
    }