Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*File summary - Prints file summary all printable, non-printable characters from any file.
- Can also works as strings extraction from any file just like GNU 'strings'. tool.
- Written by - Ha5eeB MiR (haseebmir.hm@gmail.com)
- Dated : 13/08/2018
- */
- #include <iostream>
- #include <fstream>
- #include <vector>
- std::string ReadFile(std::string file_name);
- int main()
- {
- std::string file_name;
- std::cout << "Enter file name to print summary!" << std::endl;
- std::cin>> file_name;
- std::string ascii_data = ReadFile(file_name);
- if(!ascii_data.empty()){
- int cntrl_count = 0,graph_count = 0,space_count = 0,null_count = 0,strings_count = 0;
- std::vector<uint8_t> cntrl_vec,print_vec,space_vec,string_s;
- /* Minimum length of sequence of graphic chars to trigger output. (same as of (GNU strings tool) */
- static int string_min = 4;
- for(auto& c : ascii_data) {
- if(::iscntrl(c)) {
- cntrl_count++;
- cntrl_vec.push_back(c);
- }
- if(::isspace(c)) {
- space_count++;
- space_vec.push_back(c);
- }
- if(::isprint(c) || c == '\0') {
- graph_count++;
- if(::isprint(c)){
- string_s.push_back(c);
- strings_count++;
- }
- if(string_min <= strings_count && c == '\0') {
- for(auto ss : string_s)
- print_vec.push_back(ss);
- print_vec.push_back('\0');
- string_s.clear();
- strings_count = 0;
- }
- }
- }
- std::cout << "File summary : " << std::endl;
- std::cout <<"\nNon-printable characters : " << cntrl_count << std::endl;
- for(auto& v : cntrl_vec) std::cout << " '" << v << "' ";
- std::cout <<"\nPrintable characters : " << graph_count << std::endl;
- for(auto& v : print_vec) {
- if(v == '\0') {
- std::cout << "\n";
- }
- std::cout << v;
- }
- std::cout <<"\nSpaces : " << space_count << std::endl;
- for(auto& v : space_vec) std::cout << " _ ";
- }
- else
- {
- return EXIT_FAILURE;
- }
- return EXIT_SUCCESS;
- }
- std::string ReadFile(std::string file_name)
- {
- /*Buffers to store output data from file.*/
- std::string str_buf;
- try {
- std::ifstream in_stream(file_name,std::ifstream::binary);
- if (in_stream) {
- /*Get the length of the file.*/
- in_stream.seekg (0, in_stream.end);
- int64_t length = in_stream.tellg();
- in_stream.seekg (0, in_stream.beg);
- char* data_buf = new char [length];
- /*Read data in chunks into buffer.*/
- in_stream.read(data_buf,length);
- if (!in_stream) {
- std::cerr << "Error : " << in_stream.gcount() << " characters could be read!" << std::endl;
- }
- in_stream.close();
- std::string s_buf(data_buf,length);
- str_buf = s_buf;
- delete[] data_buf;
- } else {
- throw std::exception();
- }
- }
- catch(std::exception const& ex) {
- std::cerr << "Error : " << file_name << ": No such file or directory" << std::endl;
- }
- return str_buf;
- }
Add Comment
Please, Sign In to add comment