C语言编程确定一个文件的真实类型

要使用C语言编程确定一个文件的真实类型,您可以使用标准库函数和系统相关的函数来实现。以下是一个简单的示例程序,它通过检查文件的魔法数字(Magic Number)来识别文件的类型。请注意,此示例仅用于学习目的,实际应用中可能需要更全面的方法。

 

```c

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

 

#ifdef _WIN32

#include <windows.h>

#else

#include <unistd.h>

#include <sys/stat.h>

#endif

 

// 常见的文件类型魔法数字

unsigned char pdf_magic[] = { 0x25, 0x50, 0x44, 0x46 };

unsigned char png_magic[] = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A };

unsigned char jpeg_magic[] = { 0xFF, 0xD8, 0xFF };

 

char* getFileType(const char* filename) {

    FILE* file = fopen(filename, "rb");

    if (!file) {

        return "File not found";

    }

 

    unsigned char buf[32];

    size_t bytes_read = fread(buf, 1, sizeof(buf), file);

    fclose(file);

 

    // 检查PDF文件的魔法数字

    if (memcmp(buf, pdf_magic, sizeof(pdf_magic)) == 0) {

        return "PDF";

    }

 

    // 检查PNG文件的魔法数字

    if (memcmp(buf, png_magic, sizeof(png_magic)) == 0) {

        return "PNG";

    }

 

    // 检查JPEG文件的魔法数字

    if (memcmp(buf, jpeg_magic, sizeof(jpeg_magic)) == 0) {

        return "JPEG";

    }

 

    return "Unknown file type";

}

 

int main(int argc, char* argv[]) {

    if (argc != 2) {

        printf("Usage: %s <file>\n", argv[0]);

        return 1;

    }

 

    char* filename = argv[1];

    char* file_type = getFileType(filename);

    printf("File type of %s is: %s\n", filename, file_type);

    return 0;

}

```

 

这个示例程序定义了一些常见文件类型的魔法数字,然后通过比较文件开头的字节来判断文件类型。需要注意的是,此方法并不适用于所有文件类型,仅作为示例。为了支持更多文件类型,您需要扩展魔法数字列表并修改`getFileType`函数。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值