In Chapter 6 of Beginning C++ Programming, I followed the instructions to code a search program. However, I still have error despite going over the code several times.
// Using Classes
#include <iostream>
#include <string>
#include <io.h>
usingnamespace std;
// class that encapsulate searching for a file with a pattern
// using the C runtime functions
class search_handle
{
// this is the data member that will be managed
intptr_t handle;
// public here means public to the containing class
public:
search_handle() : handle(-1) {}
search_handle(intptr_t p) : handle(p) {}
voidoperator=(intptr_t p) { handle = p; }
// DO NOT ALLOW COPYING
search_handle(search_handle& h) = delete;
voidoperator=(search_handle& h) = delete;
// move sematics allowed
search_handle(search_handle&& h) { close(); handle = h.handle; }
voidoperator=(search_handle&& h) { close(); handle = h.handle; }
// allow implicit conversion to a bool no check that the
// data member is valid
operatorbool() const { return (handle != -1); }
// allow implicit conversion to an intptr_t
operator intptr_t() const { return handle; }
// allow callers to explicitly release the handle
void close() { if (handle != -1) _findclose(handle); handle = 0; }
// allow automatic release of the handle
~search_handle() { close(); }
};
class file_search
{
// class used to manage the lifetime of a search handle
// used by the C runtime _findfirst/_findnext functions
search_handle handle;
string search;
// these are the public interface of the class
public:
// we can create objects with a C or C++ string
file_search(constchar* str) : search(str) {}
file_search(const string& str) : search(str) {}
// get access to the search string
constchar* path() const { return search.c_str(); }
// explicitly close the search
void close() { handle.close(); }
// get the next value in the search
bool next(string& ret)
{
_finddata_t find();
if (!handle)
{
// the first call to get the search handle
handle = _findfirst(search.c_str(), &find);
if (!handle)
returnfalse;
}
else
{
// subsequent calls on the search handle
if (-1 == _findnext(handle, &find))
returnfalse;
}
// return the name of the file found
ret = find.name;
returntrue;
}
};
void usage()
{
cout << "usage: search pattern" << endl;
cout << "pattern is the file or folder to search for "
<< "with or without wildcards * and ?" << endl;
}
int main(int argc, char* argv[])
{
if (argc < 2)
{
usage();
return 1;
}
file_search files(argv[1]);
cout << "searching for " << files.path() << endl;
string file;
while (files.next(file))
{
cout << file << endl;
}
return 0;
}
line 59 - error C2664: has to do with intptr _findfirst
line 66 - error C2664: has to do with int _findnext
line 71 - error C2228: left of '.name' must have a class/struct/union
I am using Microsoft Visual Studio 2017, the free download.