C语言获取文件大小(字节)


代码

核心代码

	FILE *pfile = nullptr;
	int ret = fopen_s(&pfile, str.c_str(), "rb");

	/// 0 = 打开成功,
	if (0 == ret)
	{
		if (pfile)
		{
			/// 将文件指针移动到文件尾
			fseek(pfile, 0, SEEK_END);
			unsigned int file_length_bytes = ftell(pfile);
			fclose(pfile);
			pfile = nullptr;

			std::cout << "the length of the file is " << file_length_bytes << "\n\n\n";
		}
		else
		{
			;/// pfile 文件指针为null
		}
	}
	else
	{
		;/// 打开失败
	}

完整代码


#include <iostream>

/// 判断文件是否存在
bool is_exist_file_(std::string&& str_file)
{
	struct stat st;

	return (0 == stat(str_file.c_str(), &st));
}


int main()
{
	std::string str = "C:\\EnvPath_VAPS_XT_4_2.txt";

	bool is_exist = is_exist_file_(std::move(str));
	if (!is_exist)
		return 0;

	FILE *pfile = nullptr;
	int ret = fopen_s(&pfile, str.c_str(), "rb");

	/// 0 = 打开成功,
	if (0 == ret)
	{
		if (pfile)
		{
			/// 将文件指针移动到文件尾
			fseek(pfile, 0, SEEK_END);
			unsigned int file_length_bytes = ftell(pfile);
			fclose(pfile);
			pfile = nullptr;

			std::cout << "the length of the file is " << file_length_bytes << "\n\n\n";
		}
		else
		{
			;/// pfile 文件指针为null
		}
	}
	else
	{
		;/// 打开失败
	}


	std::cout << is_exist << "\n\n\n";
}


结果


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM