简体   繁体   English

如何在c中获取文件长度?

[英]How to get a file length in c?

I just have a quick question about how to get the length of a file containing hexadecimal numbers. 我只是有一个关于如何获取包含十六进制数字的文件长度的快速问题。 For example: 例如:

724627916C

The only way I can think is to convert hex value to binary: 我能想到的唯一方法是将十六进制值转换为二进制:

724627916C => 0111001001000110001001111001000101101100

then count the bits of binary value. 然后计算二进制值的位数。 Just wondering if this is the correct way? 只是想知道这是不是正确的方法? Thanks 谢谢

No, this is not the correct way. 不,这不是正确的方法。

FILE *fp = fopen("filename", "rb");
fseek(fp, 0, SEEK_END);
int lengthOfFile = ftell(fp);
fclose(fp);

In principle: Open a file, seek to the end and retrieve your current position. 原则上:打开文件,搜索到最后并检索当前位置。 What you'll get is the number of bytes in the file. 你会得到的是文件中的字节数。

Edit: Your question is a little unclear. 编辑:你的问题有点不清楚。 Do you want to retrieve the number of bytes in the file, or the number of bytes represented by the hexadecimal string in the file? 是否要检索文件中的字节数,或者文件中十六进制字符串表示的字节数? If the latter is the case, and you don't have any whitespaces in your file, just divide the number of bytes returned by the method above by 2. 如果是后一种情况,并且文件中没有任何空格,只需将上述方法返回的字节数除以2即可。

在类似于* x的操作系统中, stat可用stat目的。

Try this answer for some help. 试试这个答案以获得一些帮助。 If that doesn't work, Google has plenty of information on determining file size in C. 如果这不起作用,谷歌有很多关于用C确定文件大小的信息。

If you want to count the bits, it would be simpler to set up an array that tells you how many bits are set in each hex digit (indexed by character code), and then add things up without explicitly converting to binary. 如果你想对这些位进行计数,那么设置一个数组可以更简单地告诉你在每个十六进制数字中设置了多少位(由字符代码索引),然后在不明确转换为二进制的情况下添加内容。

Assuming C99: 假设C99:

static bits_map[256] =
{
    ['0'] = 0, ['1'] = 1, ['2'] = 1, ['3'] = 2,
    ['4'] = 1, ['5'] = 2, ['6'] = 2, ['7'] = 3,
    ['8'] = 1, ['9'] = 2,
    ['a'] = 2, ['b'] = 3, ['c'] = 2, ['d'] = 3,
    ['e'] = 3, ['f'] = 4,
    ['A'] = 2, ['B'] = 3, ['C'] = 2, ['D'] = 3,
    ['E'] = 3, ['F'] = 4,
};

size_t n_bits = 0;
int c;
while ((c = getchar()) != EOF)
    n_bits += bits_map[c];

printf("Number of bits set: %zd\n", n_bits);

File length in C goes use the function _filelength() C中的文件长度使用函数_filelength()

#include <io.h>

int fn, fileSize;
FILE * f = fopen(&String, "rb");
if (f)
{
  fn = _fileno(f);
  fileSize = _filelength(fn);
}
fclose(f);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM