1

I would like to know how this code would look in C++:

<?php

$read=fread(fopen('cookie.txt', 'r'), filesize('cookie.txt'));


$pattern = "/[a-f0-9]{32}/";
preg_match($pattern, $read, $matches);
echo $matches[0];

?>
0

2 Answers 2

1

Navaz makes it look like reading a file in C++ is hard or requires pointers. Neither is the case. In fact, the file can be read in one line:

std::ifstream in("cookie.txt");
string str(static_cast<stringstream const&>(stringstream() << in.rdbuf()).str());

(This may look daunting but it’s conceptually simple. We read the file into a string stream and copy the result into a string str).

The rest of the solution would be identical.

Sign up to request clarification or add additional context in comments.

1 Comment

I often forget to use this way to read files. :(.. +1 for reminding me this once again. :-)
1

Use boost::regex. The following is an example which may not be exact equivalent to your PHP code.I don't know PHP, so test it extensively before you use it. :-)

#include <string>
#include <iostream>
#include <fstream>
#include <boost/regex.hpp>

std::ifstream file("cookie.txt");
std::stringstream input;
input << file.rdbuf();
file.close();

boost::regex pattern("/[a-f0-9]{32}/");
boost::match_results<std::string::const_iterator> results;
if(boost::regex_match(input.str(), results, pattern, boost::match_default |  boost::match_partial))
{
    //results contains the matches
}

3 Comments

boost::match_results<std::string::const_iterator> results; if(boost::regex_match(input.str(), results, pattern, boost::match_default | boost::match_partial)) { //results contains the matches } errors :S
@rammstein: what error? can you post the error? Also have you installed boost library on your machine?
this is a part of errors : mplementation<char>::error_string(boost::regex_constants::error_type) const]+0x9a): undefined reference to boost::re_detail::get_default_error_string(boost::regex_constants::error_type)' main.cpp:(.text._ZNK5boost9re_detail31cpp_regex_traits_implementationIcE12error_stringENS_15regex_constants10error_typeE[boost::re_detail::cpp_regex_traits_implementation<char>::error_string(boost::regex_constants::error_type) const]+0x129): undefined reference to boost::re_detail::get_default_error_string(boost::regex_constants::error_type)' collect2: ld returned 1 exit status

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.