当文件具有相同的字符数时,为什么文件大小不同?

时间:2011-10-31 14:03:57

标签: c file encoding utf-8

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

当“huffman.txt”包含一个简单的字符串,例如“你好,你好吗”,它会给出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);
}

2 个答案:

答案 0 :(得分:1)

这与编码有关。

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

查看正在发生的事情的最简单方法是使用

打印每个字符
char c;
/* Read file. */
while (c = fgetc())
  printf ("%c", c)

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

答案 1 :(得分:0)

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

相关问题