我怎样才能知道我用C写的应用程序打开的文件的大小?我想知道文件的大小,因为我想将加载文件的内容放入一个字符串中,这个字符串是使用malloc()
分配的。仅仅写malloc(10000*sizeof(char));
不是一个好主意。
发布于 2008-10-26 20:57:30
您需要查找到文件的末尾,然后询问位置:
fseek(fp, 0L, SEEK_END);
sz = ftell(fp);
然后,您可以向后查找,例如:
fseek(fp, 0L, SEEK_SET);
或者(如果要从头开始)
rewind(fp);
发布于 2008-10-26 20:59:32
使用标准库:
假设您的实现很有意义地支持SEEK_END:
fseek(f, 0, SEEK_END); // seek to end of file
size = ftell(f); // get current file pointer
fseek(f, 0, SEEK_SET); // seek back to beginning of file
// proceed with allocating memory and reading the file
Linux/POSIX:
您可以使用stat
(如果您知道文件名)或fstat
(如果您有文件描述符)。
以下是stat的示例:
#include <sys/stat.h>
struct stat st;
stat(filename, &st);
size = st.st_size;
Win32:
您可以使用GetFileSize或GetFileSizeEx。
发布于 2008-10-26 21:17:18
如果有文件描述符,fstat()
将返回一个包含文件大小的stat结构。
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
// fd = fileno(f); //if you have a stream (e.g. from fopen), not a file descriptor.
struct stat buf;
fstat(fd, &buf);
off_t size = buf.st_size;
https://stackoverflow.com/questions/238603
复制相似问题