c++中使用 fstream获取文件大小的方法
时间: 2024-05-01 12:15:43 浏览: 22
获取文件大小的方法有三种,分别为利用ifstream、C函数、Windows _stat函数。
1.利用ifstream[^1]
```c++
#include <fstream>
#include <string>
size_t GetFileSize(const std::string& file_name){
std::ifstream file(file_name.c_str(), std::ios::binary | std::ios::ate);
return static_cast<size_t>(file.tellg());
}
```
2.利用C函数
```c++
#include <stdio.h>
#include <stdlib.h>
long GetFileSize(const char* filename){
FILE* fp = fopen(filename, "rb");
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
fclose(fp);
return size;
}
```
3.利用Windows _stat函数
```c++
#include <sys/stat.h>
#include <iostream>
typedef unsigned long DWORD;
DWORD GetFileSize(const char* file){
struct stat stat_buf;
int rc = stat(file, &stat_buf);
return rc == 0 ? stat_buf.st_size : -1;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)