Im having problems understanding how to write a PGM file using data. This function i have overwrites the existing txt document instead of creating a PGM file. Im unsure whether my issue is lies within my Read_text function or somewhere else. Can anyone help me understand this issue and fix it please?
double* read_text(char *fileName, int sizeR, int sizeC)
{
double* data = new double[sizeR*sizeC];
int i = 0;
std::ifstream myfile(fileName);
if (myfile.is_open())
{
while (myfile.good())
{
if (i>sizeR*sizeC - 1) break;
myfile >> *(data + i);
std::cout << *(data+i) << ' '; //This line display the converted data on the screen, you may comment it out.
i++;
}
myfile.close();
}
else std::cout << "Unable to open file";
std::cout << i;
return data;
}
void write_pgm(char *filename, double *data, int sizeR, int sizeC, int Q)
{
int i, j;
unsigned char *image;
std::ofstream myfile;
image = (unsigned char *) new unsigned char[sizeR*sizeC];
// convert the integer values to unsigned char
for (i = 0; i<sizeR*sizeC; i++)
image[i] = (unsigned char)data[i];
myfile.open(filename, std::ios::out | std::ios::binary | std::ios::trunc);
if (!myfile) {
std::cout << "Can't open file: " << filename << std::endl;
exit(1);
}
myfile << "P5" << std::endl;
myfile << sizeC << " " << sizeR << std::endl;
myfile << Q << std::endl;
myfile.write(reinterpret_cast<char *>(image), (sizeR*sizeC)*sizeof(unsigned char));
if (myfile.fail()) {
std::cout << "Can't write image " << filename << std::endl;
exit(0);
}
myfile.close();
std::cout << "Finsihed " << std::endl;
delete[] image;
}
void main() {
double* data = read_text("Wally_grey.txt", rows(), columns());
std::cout << data << std::endl;
write_pgm("Wally_grey.txt",data, rows(), columns(), 255);
getchar();
}