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