如何在 C 中获取文件的大小? [英] How can I get a file's size in C?
本文介绍了如何在 C 中获取文件的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何知道我用 C 编写的应用程序打开的文件的大小?我想知道大小,因为我想将加载文件的内容放入一个字符串中,我使用 malloc()
分配该字符串.只写 malloc(10000*sizeof(char));
恕我直言是个坏主意.
How can I find out the size of a file I opened with an application written in C ?
I would like to know the size, because I want to put the content of the loaded file into a string, which I allocate using malloc()
. Just writing malloc(10000*sizeof(char));
is IMHO a bad idea.
推荐答案
需要查找到文件末尾然后询问位置:
You need to seek to the end of the file and then ask for the position:
fseek(fp, 0L, SEEK_END);
sz = ftell(fp);
然后你可以找回,例如:
You can then seek back, e.g.:
fseek(fp, 0L, SEEK_SET);
或(如果想从头开始)
rewind(fp);
这篇关于如何在 C 中获取文件的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文