【问题标题】:Unable to calculate size of a large bmp file using C in android [closed]无法在android中使用C计算大型bmp文件的大小[关闭]
【发布时间】:2012-12-31 05:15:43
【问题描述】:

我正在尝试使用 android ndk 中的 C 函数计算大型 bmp 文件的大小。我正在使用以下代码:-

int getSizeOfCapturedImage(char * imagePath) {
    FILE *imageFile = fopen(imagePath, "rb");
    long sizeOfImageFile = 0;

    if (imageFile == NULL) {
        printf("file not found!\n"); //handle error
        return 1;
    } else {
        fseek(imageFile, 0, SEEK_END);
        sizeOfImageFile = ftell(imageFile);
        printf("size of ImageFile is %1dB\n", sizeOfImageFile);
        fclose(imageFile);
    }
    return sizeOfImageFile;
}

但是,当 bmp 文件的大小大于 120 字节时,此功能无法正常工作。文件不知何故无法打开,文件指针 *imageFile 变为 NULL。

谁能告诉我为什么会这样和/或有其他出路吗?

【问题讨论】:

  • 您已经使用磁盘上相同位置的相同文件名验证了这一点,只替换文件本身并重新运行程序?除非您的内存太紧,甚至无法分配 FILE 缓冲区,否则文件大小不会对这段代码产生任何影响,因此唯一的逻辑变量是传入的名称可能已损坏。打印文件名和 errno 以及您的文件未找到消息 printf("File not found : %d, %s\n", errno, imagePath); 并确保它有效。
  • 正确的 imagePath 作为参数传递给文件打开函数。我验证过了。
  • 那么在验证errno的报告值是...?
  • ...蟋蟀。也许errno 提供了一些信息?除非 OP 提供更多信息,否则投票结束。

标签: c file-io android-ndk


【解决方案1】:

查看this SO post,这里有一个不需要您使用 fopen 打开文件的解决方法。使用的代码是:

#include <sys/stat.h>

ssize_t fsize(const char *filename) {
    struct stat st; 

    if (stat(filename, &st) == 0)
        return st.st_size;

    return -1; 
}

@H2CO3 说得好:

数据类型:ssize_t 这个数据类型用来表示大小 可以在单个操作中读取或写入的块。这是 类似于 size_t,但必须是有符号类型。

【讨论】:

  • off_t 用于偏移量。返回size_t(如果您不想处理无符号整数溢出,则返回ssize_t)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-06
  • 1970-01-01
  • 1970-01-01
  • 2019-01-06
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多