【问题标题】:Why is file size different when the files have the same number of characters?当文件具有相同数量的字符时,为什么文件大小不同?
【发布时间】:2011-12-18 18:41:34
【问题描述】:

在这里,当我使用 stat() 获取文件大小时,它会给出不同的输出,为什么会这样?

当“huffman.txt”包含像“Hi how are you”这样的简单字符串时,它会给出file_size = 14。但是当“huffman.txt”包含像“άSUä5Ñ®qøá”F”这样的字符串时,它会给出file size = 30

#include <sys/stat.h>
#include <stdio.h>

int main() 
{
    int size = 0;
    FILE* original_fileptr = fopen("huffman.txt", "rb");
    if (original_fileptr == NULL) {
        printf("ERROR: fopen fail in %s at %d\n", __FUNCTION__, __LINE__);
        return 1;
    }
    /*create variable of stat*/
    struct stat stp = { 0 };
    stat("huffman.txt", &stp);
    /*determine the size of data which is in file*/
    int filesize = stp.st_size;
    printf("\nFile size is %d\n", filesize);
}

【问题讨论】:

  • 为什么要先打开文件? stat 不需要那个。
  • 并非文件中的所有字符都可以打印,但它们仍在文件中。

标签: c file encoding utf-8


【解决方案1】:

如果您问为什么具有相同字符数的不同字符串可能具有不同的字节大小,请阅读UTF-8

【讨论】:

    【解决方案2】:

    这与编码有关。

    纯文本英文字符以 ASCII 编码,其中每个字符为一个字节。 但是,非纯文本英语中的字符以 Unicode 编码,每个字符为 2 字节。

    查看正在发生的事情的最简单方法是使用打印每个字符

    char c;
    /* Read file. */
    while (c = fgetc())
      printf ("%c", c)
    

    您将了解文件大小不同的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 2018-03-24
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多