C 文件检查文件是否为空或包含 ASCII 文本

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

我正在尝试编写一个程序,它应该能够将文件作为终端的输入,然后确定该文件是空的还是以 ASCII 文本编写的。但我一直收到分段错误 11。

我的代码如下:

#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);
}

关于为什么的任何想法?

fseek 将一个 FILE* 作为参数,而您给它一个 unsigned char* - 将 &c 更改为文件。

fseek(&c, 0, SEEK_END);

这里你应该传递文件描述符,比如

fseek(file, 0, SEEK_END);

1] fseek 没有第一个参数 unsgined char*,但是 FILE*.

fseek(file, 0, SEEK_END);

2] 您不应该使用 unsigned char / char 来检查 EOF,请务必使用 int

3] 工作和更简单的代码

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;
}