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

标签 c file segmentation-fault ascii fopen

我正在尝试编写一个程序,该程序应该能够将文件作为终端的输入,然后确定该文件是否为空或以 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);
}

有什么想法可以解释为什么吗?

最佳答案

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

fseek(文件, 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;
}

关于C 文件检查文件是否为空或包含 ASCII 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45565668/

相关文章:

c - 使用 C 段错误进行字符串操作

c++ - 在 imageStore() 之后为 3D 纹理生成 MipMap 级别

c - 当线程在已解锁的互斥锁上调用 pthread_mutex_unlock 时会发生什么

c - strcpy() 不适用于某些字符串,但不适用于其他字符串

c - 如何在 c 中制作二进制文件 ---- struct within a struct

c++ - 读取大文件的小块(C++)

java - 如何检查用户输入的字符串是否包含文件扩展名

c - 段错误和链表的未知问题

c - Linux中的线程并发

node.js - 如何在node.js中上传文件时中断?