Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,039 questions

52,004 answers

573 users

How to get the size of a file in C++

6 Answers

0 votes
#include <iostream>
#include <fstream>

int main()
{
	std::streampos begin, end;
	std::ifstream afile("d:\\data.txt");

	begin = afile.tellg();

	afile.seekg(0, std::ios::end);
	end = afile.tellg();

	afile.close();

	std::cout << end - begin << std::endl;

	return 0;
}

/*
run:

15

*/

 



answered Nov 16, 2017 by avibootz
edited Nov 16, 2017 by avibootz
0 votes
#include <iostream>
#include <fstream>

int main() 
{
	const char *filename = "d:\\data.txt";

	std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary);

	std::cout << in.tellg() << std::endl;

	return 0;
}

/*
run:

15

*/

 



answered Nov 16, 2017 by avibootz
0 votes
#include <iostream>
#include <fstream>

std::ifstream::pos_type filesize(const char* filename)
{
	std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary);

	return in.tellg();
}

int main() 
{
	const char *filename = "d:\\data.txt";

	std::cout << filesize(filename) << std::endl;

	return 0;
}

/*
run:

15

*/

 



answered Nov 16, 2017 by avibootz
0 votes
#include <iostream>
#include <fstream>

long filesize(std::string filename)
{
	struct stat stat_struct;

	int result = stat(filename.c_str(), &stat_struct);

	return result == 0 ? stat_struct.st_size : -1;
}


int main() 
{
	const char *filename = "d:\\data.txt";

	std::cout << filesize(filename) << std::endl;

	return 0;
}

/*
run:

15

*/

 



answered Nov 16, 2017 by avibootz
0 votes
#include <iostream>
#include <fstream>

int main()
{
	std::streampos size;

	std::ifstream file("d:\\data.bin", std::ios::ate);

	if (file.is_open())
	{
		size = file.tellg();

		file.close();

		std::cout << size << std::endl;
	}
	else std::cout << "Error open file" << std::endl;

	return 0;
}

/*
run:

23

*/

 



answered Nov 16, 2017 by avibootz
edited Nov 16, 2017 by avibootz
0 votes
#include <iostream>
#include <fstream>

int main() 
{
	std::streampos size;

	std::ifstream file("d:\\data.txt", std::ios::ate);

	if (file.is_open())
	{
		size = file.tellg();
		
		file.close();

		std::cout << size << std::endl;
	}
	else std::cout << "Error open file" << std::endl;

	return 0;
}

/*
run:

15

*/

 



answered Nov 16, 2017 by avibootz
...