Copy a part of a file to another using iterators - c++

I'm still practicing C++ and I have issues with char iterators over filestreams.
I want to copy a part of a file to another (temporary) file. I want to find a particular string in the first file (I used std::find algorithm), in order to know where I can "cut" the part of the file to be copied (hope that makes sense). My problem is that with the following code I have a compilation error that I don't really understand.
The part of my code in question looks like this:
ifstream readStream(fileName.c_str());
istreambuf_iterator<char> fStart(readStream);
istreambuf_iterator<char> fEnd;
auto position = find(fStart, fEnd, refToReplace); // refToReplace is a std::string
if (position != fEnd){ // If the reference appears in the file
ofstream tempStream("temp.fsr"); // create the temp file
copy(fStart, position , ostreambuf_iterator<char>(fluxTemp)); // and copy the part I want (before the matching string)
}
else{
continue;
}
And the compilation error I'm getting in "stl_algo.h":
error: no match for 'operator==' in '__first.std::istreambuf_iterator<_CharT, _Traits>::operator*<char, std::char_traits<char> >() == __val'
Thank you in advance.

The compilation error should come with an instantiation backtrace that tells you which call you made ultimately caused the error.
In your case, this will point at the find call. find looks for a single element, and the element type of your iterators is a single character, but you pass a string. (Based on your description. Your snippet doesn't actually tell us what the type of refToReplace is.)
The algorithm you're looking for is search, but that requires forward iterators, which streambuf iterators are not.
You will need to choose a different approach.

Related

Why is my private member displayed as another type than it is defined as?

I'm currently working on a project in C++ and I'm just not allowed to push_back on my vector (compile error).
The method where everything seems to go wrong looks like this:
DetectionResult DetectionManager::Update(DetectionInput& input) const
{
std::vector<DetectionResultUnfiltered> results;
results.reserve(m_detectionModels.size());
for (auto& detectionModel : m_detectionModels)
(
std::future<void> future = std::async(std::launch::async, UpdateDetectionModelAsynchronously, detectionModel, &results, &input);
m_futures.push_back(future); // <-- Compile error only on this line
)
}
I think it is rather unimportant what exactly the other called method does and how those types are structured exactly. The only important thing should be that the field m_futures is of the type std::vector<std::future<void>>.
Even when hovering the m_futures in Visual Studio within that method, it clearly shows me that it is of the correct type (field) std::vector<std::future<void>> DetectionManager::m_futures.
But still the .push_back() call is underlined in red, and when hovered it shows the following error: no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back [with _Ty=std::future<void>, _Alloc=std::allocator<std::future<void>>]" matches the argument list and object (the object has type qualifiers that prevent a match) - argument types are: (std::future<void>) - object type is: const std::vector<std::future<void>, std::allocator<std::future<void>>>
I'm pretty sure my vector is not really handled as a vector in this current case, because when auto completing the method calls on my vector I don't get even a suggestion for .push_back() or .emplace_back() or something like this. I think it is handled as an object of a type I imported from another library (opencv::mat or something like that), because at some point it was even shown like that when hovered.
And by the way,
the method call is not shown as an error when I do this:
(static_cast<std::vector<std::future<void>>>(m_futures)).push_back(future);
so by explicitly casting it to a vector it seems to work again.
I just don't know exactly what happens here. I've traced down and commented some includes to make sure nothing weird was included. And while doing that I figured out that I don't get any errors highlighted within the DetectionManager.h even when commenting out the #include (Even if not including ANYTHING in the .h at all, only the #include is needed when working with that type).
It doesn't even work on other vectors as well, so when implementing an example vector which only holds bools, I don't need to include the and everything looks right according to Visual Studio, which is weird enough since I didn't include or which I'm using as well.
Does anyone have any idea what it might be? Or how to track down this error?
Big thanks in advance!
As Borgleader correctly pointed out, the method was marked as const - but when pushing back, I am modifying the class field which is obviously not allowed.
The const was a leftover from an older design I just reworked and thus I completely forgot about it.
That paired with some other weird errors I had before (like the field being shown as a complete different type from some library I imported even though it was clearly declared as a vector) didn't help.
I still don't quite understand why my project is compiling when not including or within the header file at all even when I declare fields with those types, but at least that's not stopping me from building and running the program.

Function to call #include macro from a string variable argument?

Is it possible to have a function like this:
const char* load(const char* filename_){
return
#include filename_
;
};
so you wouldn't have to hardcode the #include file?
Maybe with a some macro?
I'm drawing a blank, guys. I can't tell if it's flat out not possible or if it just has a weird solution.
EDIT:
Also, the ideal is to have this as a compile time operation, otherwise I know there's more standard ways to read a file. Hence thinking about #include in the first place.
This is absolutely impossible.
The reason is - as Justin already said in a comment - that #include is evaluated at compile time.
To include files during run time would require a complete compiler "on board" of the program. A lot of script languages support things like that, but C++ is a compiled language and works different: Compile and run time are strictly separated.
You cannot use #include to do what you want to do.
The C++ way of implementing such a function is:
Find out the size of the file.
Allocate memory for the contents of the file.
Read the contents of the file into the allocated memory.
Return the contents of the file to the calling function.
It will better to change the return type to std::string to ease the burden of dealing with dynamically allocated memory.
std::string load(const char* filename)
{
std::string contents;
// Open the file
std::ifstream in(filename);
// If there is a problem in opening the file, deal with it.
if ( !in )
{
// Problem. Figure out what to do with it.
}
// Move to the end of the file.
in.seekg(0, std::ifstream::end);
auto size = in.tellg();
// Allocate memory for the contents.
// Add an additional character for the terminating null character.
contents.resize(size+1);
// Rewind the file.
in.seekg(0);
// Read the contents
auto n = in.read(contents.data(), size);
if ( n != size )
{
// Problem. Figure out what to do with it.
}
contents[size] = '\0';
return contents;
};
PS
Using a terminating null character in the returned object is necessary only if you need to treat the contents of the returned object as a null terminated string for some reason. Otherwise, it maybe omitted.
I can't tell if it's flat out not possible
I can. It's flat out not possible.
Contents of the filename_ string are not determined until runtime - the content is unknown when the pre processor is run. Pre-processor macros are processed before compilation (or as first step of compilation depending on your perspective).
When the choice of the filename is determined at runtime, the file must also be read at runtime (for example using a fstream).
Also, the ideal is to have this as a compile time operation
The latest time you can affect the choice of included file is when the preprocessor runs. What you can use to affect the file is a pre-processor macro:
#define filename_ "path/to/file"
// ...
return
#include filename_
;
it is theoretically possible.
In practice, you're asking to write a PHP construct using C++. It can be done, as too many things can, but you need some awkward prerequisites.
a compiler has to be linked into your executable. Because the operation you call "hardcoding" is essential for the code to be executed.
a (probably very fussy) linker again into your executable, to merge the new code and resolve any function calls etc. in both directions.
Also, the newly imported code would not be reachable by the rest of the program which was not written (and certainly not compiled!) with that information in mind. So you would need an entry point and a means of exchanging information. Then in this block of information you could even put pointers to code to be called.
Not all architectures and OSes will support this, because "data" and "code" are two concerns best left separate. Code is potentially harmful; think of it as nitric acid. External data is fluid and slippery, like glycerine. And handling nitroglycerine is, as I said, possible. Practical and safe are something completely different.
Once the prerequisites were met, you would have two or three nice extra functions and could write:
void *load(const char* filename, void *data) {
// some "don't load twice" functionality is probably needed
void *code = compile_source(filename);
if (NULL == code) {
// a get_last_compiler_error() would be useful
return NULL;
}
if (EXIT_SUCCESS != invoke_code(code, data)) {
// a get_last_runtime_error() would also be useful
release_code(code);
return NULL;
}
// it is now the caller's responsibility to release the code.
return code;
}
And of course it would be a security nightmare, with source code left lying around and being imported into a running application.
Maintaining the code would be a different, but equally scary nightmare, because you'd be needing two toolchains - one to build the executable, one embedded inside said executable - and they wouldn't necessarily be automatically compatible. You'd be crying loud for all the bugs of the realm to come and rejoice.
What problem would be solved?
Implementing require_once in C++ might be fun, but you thought it could answer a problem you have. Which is it exactly? Maybe it can be solved in a more C++ish way.
A better alternative, considering also performances etc., to compile a loadable module beforehand, and load it at runtime.
If you need to perform small tunings to the executable, place parameters into an external configuration file and provide a mechanism to reload it. Once the modules conform to a fixed specification, you can even provide "plugins" that weren't available when the executable was first developed.

Removal of unused or redundant code [duplicate]

This question already has answers here:
Listing Unused Symbols
(2 answers)
Closed 7 years ago.
How do I detect function definitions which are never getting called and delete them from the file and then save it?
Suppose I have only 1 CPP file as of now, which has a main() function and many other function definitions (function definition can also be inside main() ). If I were to write a program to parse this CPP file and check whether a function is getting called or not and delete if it is not getting called then what is(are) the way(s) to do it?
There are few ways that come to mind:
I would find out line numbers of beginning and end of main(). I can do it by maintaining a stack of opening and closing braces { and }.
Anything after main would be function definition. Then I can parse for function definitions. To do this I can parse it the following way:
< string >< open paren >< comma separated string(s) for arguments >< closing paren >
Once I have all the names of such functions as described in (2), I can make a map with its names as key and value as a bool, indicating whether a function is getting called once or not.
Finally parse the file once again to check for any calls for functions with their name as in this map. The function call can be from within main or from some other function. The value for the key (i.e. the function name) could be flagged according to whether a function is getting called or not.
I feel I have complicated my logic and it could be done in a smarter way. With the above logic it would be hard to find all the corner cases (there would be many). Also, there could be function pointers to make parsing logic difficult. If that's not enough, the function pointers could be typedefed too.
How do I go about designing my program? Are a map (to maintain filenames) and stack (to maintain braces) the right data structures or is there anything else more suitable to deal with it?
Note: I am not looking for any tool to do this. Nor do I want to use any library (if it exists to make things easy).
I think you should not try to build a C++ parser from scratch, becuse of other said in comments that is really hard. IMHO, you'd better start from CLang libraries, than can do the low-level parsing for you and work directly with the abstract syntax tree.
You could even use crange as an example of how to use them to produce a cross reference table.
Alternatively, you could directly use GNU global, because its gtags command directly generates definition and reference databases that you have to analyse.
IMHO those two ways would be simpler than creating a C++ parser from scratch.
The simplest approach for doing it yourself I can think of is:
Write a minimal parser that can identify functions. It just needs to detect the start and ending line of a function.
Programmatically comment out the first function, save to a temp file.
Try to compile the file by invoking the complier.
Check if there are compile errors, if yes, the function is called, if not, it is unused.
Continue with the next function.
This is a comment, rather than an answer, but I post it here because it's too long for a comment space.
There are lots of issues you should consider. First of all, you should not assume that main() is a first function in a source file.
Even if it is, there should be some functions header declarations before the main() so that the compiler can recognize their invocation in main.
Next, function's opening and closing brace needn't be in separate lines, they also needn't be the only characters in their lines. Generally, almost whole C++ code can be put in a single line!
Furthermore, functions can differ with parameters' types while having the same name (overloading), so you can't recognize which function is called if you don't parse the whole code down to the parameters' types. And even more: you will have to perform type lists matching with standard convertions/casts, possibly considering inline constructors calls. Of course you should not forget default parameters. Google for resolving overloaded function call, for example see an outline here
Additionally, there may be chains of unused functions. For example if a() calls b() and b() calls c() and d(), but a() itself is not called, then the whole four is unused, even though there exist 'calls' to b(), c() and d().
There is also a possibility that functions are called through a pointer, in which case you may be unable to find a call. Example:
int (*testfun)(int) = whattotest ? TestFun1 : TestFun2; // no call
int testResult = testfun(paramToTest); // unknown function called
Finally the code can be pretty obfuscated with #defineā€“s.
Conclusion: you'll probably have to write your own C++ compiler (except the machine code generator) to achieve your goal.
This is a very rough idea and I doubt it's very efficient but maybe it can help you get started. First traverse the file once, picking out any function names (I'm not entirely sure how you would do this). But once you have those names, traverse the file again, looking for the function name anywhere in the file, inside main and other functions too. If you find more than 1 instance it means that the function is being called and should be kept.

Ignoring Syntax Errors

I have a file that contains an arbitrary number of lines of c++ code, each line of which is self-contained (meaning it is valid by itself in the main function). However, I do not know how many, if any, of the lines will have valid c++ syntax. An example file might be
int length, width; // This one is fine
template <class T className {}; // Throws a syntax error
What I want to do is write to a second file all the lines that have valid syntax. Currently, I've written a program in python that reads each line, places it into the following form
int main() {
// Line goes here
return 0;
}
and attempts to compile it, returning True if the compilation succeeds and False if it doesn't, which I then use to determine which lines to write to the output file. For example, the first line would generate a file containing
int main() {
int length, width;
return 0;
}
which would compile fine and return True to the python program. However, I'm curious if there is any sort of try-catch syntax that works with the compiler so I could put each line of the file in a try-catch block and write it to the output if no exception is thrown, or if there's a way I can tell the compiler to ignore syntax errors.
Edit: I've been asked for details about why I would need to do this, and I'll be the first to admit it's a strange question. The reason I'm doing this is because I have another program (of which I don't know all the implementation details) that writes a large number of lines to a file, each of which should be able to stand alone. I also know that this program will almost certainly write lines that have syntax errors. What I'm trying to do is write a program that will remove any invalid lines so that the resulting file can compile without error. What I have in my python program right now works, but I'm trying to figure out if there is a simpler way to do it.
Edit 2: Though I think I've got my answer - that I can't really play try-catch with the compiler, and that's good enough. Thanks everyone!
Individual lines of code that are syntactically correct in the context of a C++ source file are not necessarily syntactically correct by themselves.
For example this:
int length, width;
happens to be valid either as part of a main function or by itself -- but it has a different meaning (by itself it defines length and width as static objects).
This:
}
is valid in context, but not by itself.
There is typically no way for a compiler to ignore syntax errors. Once a syntax error has been encountered, the compiler has no way to interpret the rest of the code.
When you're reading English text, adfasff iyufoyur; ^^$(( -- but you can usually recover and recognize valid syntax after an error. Compilers for programming languages aren't designed to perform that kind of recovery; probably the nature of C++'s syntax would make it more difficult, and there's just not enough demand to make it worth doing.
I'm not sure what your criterion for a single line of code being "correct" is. One possibility might be to write the line of code to a file, contained in a definition of main:
int main() {
// insert arbitrary line here
}
and then compile the resulting source file. I'm not sure that I can see how that would be particularly useful, but it's about the closest I can come to what you're asking for.
What do you mean by "each line is self-contained"? If the syntax of a line of C++ code is valid may depend largely on the code before or after that line. A given line of code might be valid within a function, but not outside a function body. So, as long as you can't define what you mean by "self-contained" it is hard to solve your problem.

error C2679: binary '=' : no operator found which takes a right-hand operand of type 'Set<ElemType>'

I read a half-dozen forum threads relating to this error and most were due to a string declaration and the rest were not relevant to this issue.
This error is in a program that takes on input string, compares it to a list of strings then returns the strings that are close matches. That simple explanation is the gist, the actual implementation is has a bit more to it.
In a test implementation that compiled and works, I used this line of code
Set<Lexicon::CorrectionT> matches = lex.suggestCorrections(line, maxDistance);
Set is a class (uses a bst class) I am reusing from a CS106B course and Lexicon is another class from the course that I wrote and am now reusing for an unrelated project. The function suggestCorrections takes a string line and an edit distance to then compare the string and returns a Set of suggestions.
I revised the line to this
matchSet.corrections = lex.suggestCorrections(matchSet);
by defining a CorrectionT corrections within a Lexicon::MatchesT matchSet and defining matchSet in a preceding function and then passing it as a reference. MatchesT contains the fields for line and maxDistance.
From my knowledge these two lines of code are identical with the exception of the approach I am using.
So, why do I get this error "error C2679: binary '=' : no operator found which takes a right-hand operand of type 'Set'"
From my knowledge these two lines of code are identical with the exception of approach I am using.
Nope, they are completely different; one instantiates a new object, calling the copy constructor of Set<Lexicon::CorrectionT>; the other copies the object on the right to the (already created) object on the left, calling the assignment operator, which, for some reason, isn't available.
Has it been implemented in Set<>? What type is matchSet.corrections and what return type has suggestCorrections?