#include <iostream>
#include <fstream>
std::size_t get_file_contents( constchar* file_name, char text[], std::size_t sz )
{
std::size_t nchars_read = 0 ;
if( text && sz>0 ) // if the array has space for at least one char
{
if( std::ifstream file{ file_name } ) // and if the file was opened successfully
{
char ch ;
// copy up to a maximum of sz-1 characters read from the file into the array
while( nchars_read < (sz-1) && file.get(ch) ) text[ nchars_read++ ] = ch ;
}
text[nchars_read] = 0 ; // finally, null terminate the array
}
return nchars_read ; // return the number of characters that were read
}int main()
{
{
// the array is not large enough to hold the entire contents of the file
char text[35] ;
std::cout << "sizeof(text) == " << sizeof(text) << '\n' ;
std::cout << get_file_contents( __FILE__, text, sizeof(text) ) << " chars were read\n\n" ;
std::cout << text << '\n' ;
}
std::cout << "\n\n\n" ;
{
// an array that is big enough to hold the entire contents of the file
char text[35000] ;
std::cout << "sizeof(text) == " << sizeof(text) << '\n' ;
std::cout << get_file_contents( __FILE__, text, sizeof(text) ) << " chars were read\n\n" ;
std::cout << text << '\n' ;
}
}