这里,当我使用 stat()
获取文件大小时,它会给出不同的输出,为什么它会这样?
当“huffman.txt”包含一个简单的字符串(例如“Hi how are you”)时,它会给出file_size = 14
。但是,当“huffman.txt”包含类似“ÎØSUä5Ñ®qøá”F”的字符串时,它会给出文件大小= 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);
}
最佳答案
这与编码有关。
纯文本英文字符采用 ASCII 编码,每个字符都是一个字节。 然而,非纯文本英语中的字符采用 Unicode 编码,每个字符都是 2 字节。
查看正在发生的情况的最简单方法是使用打印每个字符
char c;
/* Read file. */
while (c = fgetc())
printf ("%c", c)
您将明白为什么文件大小不同。
关于c - 为什么文件的字符数相同时文件大小不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7954762/