In this code, I created files with matrix entries with names such as 1.txt, 2.txt, 3.txt and containing a total of 2 matrices. The program reads the 2 matrices in each file and multiplies the pairs of matrices it reads and prints the resulting matrix to a text file called output.txt. But when printing, it only multiplies the values in the 3.txt file, which is the last text file, and creates an output.txt file containing only those values. I want it to print the results for each input file to the same output file. But I couldn't do that. How can I do that ?
`#include <iostream>
#include <fstream>
#include <filesystem>
#include <pthread.h>
using namespace std;
#define MAX 5
#define MAX_THREAD 5
int matA[MAX][MAX];
int matB[MAX][MAX];
int matC[MAX][MAX];
int mc_rows = 0;
void* multi(void* arg)
{
int i = mc_rows++; // i denotes row number of resultant matC
for (int j = 0; j < MAX; j++)
for (int k = 0; k < MAX; k++)
matC[i][j] += matA[i][k] * matB[k][j];
pthread_exit(0);
}
void ReadMatricesFromFile(const std::filesystem::path& directory)
{
int fileCount = 0;
for (const auto& entry : std::filesystem::directory_iterator(directory))
{
if (entry.is_regular_file() && entry.path().extension() == ".txt")
{
ifstream inputFile(entry.path());
if (!inputFile)
{
cout << "Failed to open " << entry.path() << endl;
continue;
}
cout << "Reading " << entry.path() << endl;
for (int i = 0; i < MAX; i++) {
for (int j = 0; j < MAX; j++) {
inputFile >> matA[i][j];
cout << matA[i][j] << " ";
}
cout << endl;
}
cout << endl;
for (int i = 0; i < MAX; i++) {
for (int j = 0; j < MAX; j++) {
inputFile >> matB[i][j];
cout << matB[i][j] << " ";
}
cout << endl;
}
cout << endl;
inputFile.close();
fileCount++;
}
}
if (fileCount == 0)
{
cout << "No .txt files found in the directory: " << directory << endl;
}
}
int main()
{
std::filesystem::path directoryPath = "/mnt/c/users/monster/desktop/matris/txt_files"; // Klasör yolunu buraya girin
ReadMatricesFromFile(directoryPath);
pthread_t threads[MAX_THREAD];
for (int i = 0; i < MAX_THREAD; i++) {
int* p;
pthread_create(&threads[i], NULL, multi, (void*)(p));
}
for (int i = 0; i < MAX_THREAD; i++)
pthread_join(threads[i], NULL);
// Write the result matrix to output.txt
ofstream outputFile("output.txt");
if (!outputFile) {
cout << "Failed to create output.txt" << endl;
return 1;
}
for (int i = 0; i < MAX; i++) {
for (int j = 0; j < MAX; j++) {
outputFile << matC[i][j] << " ";
}
outputFile << endl;
}
outputFile.close();
return 0;
}`
1.txt file:
2.txt file:
3.txt file:
4.txt file:
OUTPUT FILE RESULTS BUT FOR ONLY 4.txt FILE :(