Open main menu

CDOT Wiki β

Changes

C/C++ FAQ

43 bytes added, 20:04, 19 November 2012
no edit summary
const char* s = "Hello world!"; cout << "s is " << SizeOfArray( s )
</source>
Lastly, with C++11 there is an even better method of doing this: std::extent. More info on this trait class can be found [http://www.cplusplus.com/reference/std/type_traits/extent/ here]. <br>Submitted by Team42.<br><br>
'''Q:''' How do you get the length of a file / read the entire file without explicitly knowing its length, and how do you use that data afterwards? <br>
'''A:''' There are several ways to read the contents of a file without knowing it's length and then split the result into usable parts.
First, you could use a string class and load the contents of the entire file into the string object. At this point you can manipulate it as any other string object (not to be confused with a char array) by using methods such as find, substr, erase, etc as outlined [http://www.cplusplus.com/reference/string/string/ here]
<sourcelang="cpp">
std::ifstream in("myfile", ios::binary);
 
std::stringstream buffer;
 
buffer << in.rdbuf();
 
std::string contents(buffer.str());
 
</source>
 
You could also use
 <sourcelang="cpp">  
inMyStream.seekg(0,std::ios_base::end);
 
std::ios_base::streampos end_pos = inMyStream.tellg();
 
return end_pos;
 
 
</source>
 
to get the length of the file without actually reading it, and then if needed read / append / modify it as required using a char array.. This method of getting a file's length can be used with char arrays / strings / vectors without problems.
 
Lastly, you could also load the file into a vector and manipulate it as a vector object from that point onwards (more advanced topic) like so
<sourcelang="cpp"
std::ifstream ifs("foobar.txt", ios::binary);
 
ifs.seekg(0, std::ios::end);
 
std::ifstream::pos_type filesize = ifs.tellg();
 
ifs.seekg(0, std::ios::beg);
 
std::vector<char> bytes(filesize);
 
ifs.read(&bytes[0], filesize);
 
 
<source>
   For any of these methods, to be able to work with the data afterwords simply use a common delimiter when originally generating the file, and then you can use methods like [http://www.cplusplus.com/reference/clibrary/cstring/strtok/ strtok] (for char array), [http://www.cplusplus.com/reference/string/string/find/ .find] combined with [http://www.cplusplus.com/reference/string/string/substr/ .substr] (string class) or use it as a vector (if that's required).<br>Submitted by Team42.<br><br>