I am trying to write a function that can interact with StockFish (a chess engine) and store the output somewhere. If you download StockFish, there is a .exe you can run and it opens a shell program where you give some commands and it outputs some text (like the best move). The issue I am having is that, I am able to write commands, but I can't read them.
This is my code:
std::unordered_map<std::string, int> stockFishPerft(std::string fenString, int depth) {
const char* stockfishPath = R"(C:\Users\1flor\CLionProjects\Chess\src\utils\stockfish\stockfish-windows-x86-64-avx2.exe > nul)";
FILE* stockfishProcess = popen(stockfishPath, "w");
std::unordered_map<std::string, int> moveCounts;
if (!stockfishProcess) {
std::cout << "Error: Could not open Stockfish process." << std::endl;
return moveCounts;
}
std::string positionCommand = "position fen " + fenString + "\n";
std::string perftCommand = "go perft " + std::to_string(depth) + "\n";
std::fprintf(stockfishProcess, "%s", positionCommand.c_str());
std::fflush(stockfishProcess);
std::fprintf(stockfishProcess, "%s", perftCommand.c_str());
std::fflush(stockfishProcess);
char buffer[4096];
while (fgets(buffer, sizeof(buffer), stockfishProcess) != nullptr) {
std::cout << buffer; // Print raw output
}
pclose(stockfishProcess);
return moveCounts;
}
When I run this, nothing gets printed. Now I have to confess that this was largely written with ChatGPT, because I don't have that much experience with C++ and I have never done something like this before. I think the reason why I can't read it because of this line:
FILE* stockfishProcess = popen(stockfishPath, "w");
Because I open this in "write" mode. But if I open it in "read" mode, I can't write my commands to StockFish. I saw something about opening it in "r+" mode, where you can read and write, but if I try that, it doesn't open the StockFish process successfully.
I did find some stuff online, but the code was very long and hard to understand. I feel like this is quite a simple task, so I figured I would ask here first, before I start writing code that felt overly complicated and stupid.