Question

I am using Visual Studio 2013

So I have to open a .ppm image file and do some work on it, but the ifstream I'm trying to use to read the data fails to open the image file. I am pretty sure the image file is in the working directory (I have created and read some simple .txt files to make sure). And even after excessive research I can't figure out what is going on.

Here's the relevant code

EDIT: I added some more code to get an idea of what I'm trying to do

Image * PPMImageReader::read(std::string filename){

        std::string line;
        int width, height, max_val;


        std::ifstream src(filename, std::ios_base::binary);



        if (src.fail()) { //failbit is always set but not badbit
            perror("Logical error on i/o operation. failbit was set\n");
            if (src.bad())
                perror("Read/writing error on i/o operation. badbit was set");
        } 
        if (!src.is_open()) { //and of course this return true
            printf("File was not opened\n");
            exit(1);
        }

     //Edited

     getline(src, line, '\n');

        if (line.empty())
            getline(src, line);

        if (line.find("P6") == std::string::npos) {
            printf("wrong format\n");
            exit(1);
        } 
Was it helpful?

Solution

As from discussed came to know the problem is relative path.

fstream support relative paths as below..

Consider the following case where your input file is one level up than exe file.

E:\MyProgramBin\YourExe.exe
E:\YourInputFile.ppm

In this case, you can create your filename as below.

filename1 = "..\YourInputFile.ppm"

and use that filename1 in ifstream

std::ifstream src(filename1, std::ios_base::binary);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top