-2

可能重复:
如何确定 C 中文件的大小?

如何在 C 中获取文件的大小?我打开了一个用 C 编写的应用程序。我想知道大小,因为我想将加载文件的内容放入一个字符串中,我使用 malloc() 进行分配。只写 malloc(10000*sizeof(char)

4

5 回答 5

3

您可以使用 fseek 和 ftell 函数:

FILE* f = fopen("try.txt","rb");
fseek(f, 0, SEEK_END);
printf("size of the file is %ld", ftell(f));
于 2012-04-17T07:06:28.147 回答
1

对于文件大小,stat、lstat 或 fstat 将是正确的选择。

请检查统计

于 2012-04-17T07:07:58.553 回答
0
    int Get_Size( string path )
{

FILE *pFile = NULL;

// get the file stream

fopen_s( &pFile, path.c_str(), "rb" );


// set the file pointer to end of file

fseek( pFile, 0, SEEK_END );

// get the file size

int Size = ftell( pFile );

// return the file pointer to begin of file if you want to read it

rewind( pFile );

// close stream and release buffer

fclose( pFile );

return Size;
}

更多答案cplusplus.com

于 2012-04-17T07:08:41.473 回答
0

您可以使用 fseek 将自己定位在文件的末尾,并为此使用 ftell():

FILE *fd;
fd = fopen("filename.txt","rb");
fseek ( fd, 0 , SEEK_END );
int fileSize = ftell(fd);

filesize 将包含以字节为单位的大小。

格科德

于 2012-04-17T07:08:59.177 回答
0

我认为有一个标准的 C 函数,但我找不到它。

If your file size is limited, you can use the solution proposed by izomorphius.

If your file can be larger than 2GB then you can use the _filelengthi64 function (see http://msdn.microsoft.com/en-us/library/dfbc2kec(v=vs.80).aspx). Unfortunately, this is a Microsoft/Windows function so it's probably not available for other platforms (although you will probably find similar functions on other platforms).

EDIT: Look at afge2's answer for the standard C function. Unfortunately, I think this is still limited to 2GB.

于 2012-04-17T07:11:42.467 回答