【问题标题】:How can I obtain a file's size in C? [duplicate]如何在 C 中获取文件的大小? [复制]
【发布时间】:2012-04-28 12:31:27
【问题描述】:

可能重复:
How do you determine the size of a file in C?

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

【问题讨论】:

  • stat(2) 系统调用,快速的谷歌应该告诉你的
  • 您的目标平台是什么?还是您打算让它成为跨平台的?
  • 另外,这里已经回答了:stackoverflow.com/questions/238603/…
  • 是否需要同时将整个文件保存在内存中?
  • 哇,其实已经有人回答了!是我的错,谢谢提醒。

标签: c file


【解决方案1】:

您可以使用 fseek 和 ftell 函数:

FILE* f = fopen("try.txt","rb");
fseek(f, 0, SEEK_END);
printf("size of the file is %ld", ftell(f));

【讨论】:

  • +1 我也经常使用的简单方法。 fstat / stat 将是另一种方式。
【解决方案2】:

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

请检查stat

【讨论】:

    【解决方案3】:
        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

    【讨论】:

      【解决方案4】:

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

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

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

      鬼神

      【讨论】:

        【解决方案5】:

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

        如果您的文件大小有限,您可以使用 izomorphius 提出的解决方案。

        如果您的文件可以大于 2GB,那么您可以使用 _filelengthi64 函数(请参阅http://msdn.microsoft.com/en-us/library/dfbc2kec(v=vs.80).aspx)。不幸的是,这是一个 Microsoft/Windows 功能,因此它可能不适用于其他平台(尽管您可能会在其他平台上找到类似的功能)。

        编辑:查看 afge2 对标准 C 函数的回答。不幸的是,我认为这仍然限于 2GB。

        【讨论】:

          猜你喜欢
          • 2011-08-15
          • 2012-08-23
          • 1970-01-01
          • 2010-11-25
          • 2023-01-11
          • 2011-09-29
          • 1970-01-01
          相关资源
          最近更新 更多