ifstream.read only reads part of the file

I'm trying to make a simple image converter (ppm format to a custom one) and i'm having a problem with the ifstream.read method. Despite having this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
int rows,cols, maxV;
    char header [100], *ptr;


    std::ifstream im;
    //open image in binary format
    im.open(name.c_str(), std::ios::in | std::ios::binary);

    if (!im)
    {
        std::cout << "Can't read image!" << std::endl;
        exit(1);
    }

    //read the header of the image
    im.getline(header, 3,'\n');
    //test if header is P6
    if ((header[0] != 80) || (header[1] != 54))
    {
        std::cout << "Image" << name << "is not .ppm format" << std::endl;
    }

    //get next line for height and width
    im.getline(header,100,'\n');
    //dont read the comments
    while (header[0] == '#')
        im.getline(header,100,'\n');

    //number of columns, rows
    cols = strtol(header, &ptr, 0);
    rows = strtol(header, &ptr, 0);
    maxV = strtol(header, &ptr, 0);

    const int rows1=rows;
    const int cols1=cols;


    Component * tbuffer;
    const_cast<Component*> (tbuffer);
    tbuffer = new Component[rows1*cols1 * 3];

    im.read((char *)tbuffer, cols*rows * 3);
    std::cout << tbuffer[3000000] << std::endl;
    im.close();


It only reads 2.700.007 elements out of 4.320.000 of the image i'm trying to read. so tbuffer[3.000.000] will "cout" NULL. Am i missing anything?

About component from other class: typedef unsigned char Component;

The image i'm trying to read is 1200*1200

Lines 30 - 32 don't look right to me, I think the y should be something like
1
2
3
4
//number of columns, rows
    cols = strtol(header, &ptr, 0);
    rows = strtol(ptr, &ptr, 0);
    maxV = strtol(ptr, &ptr, 0);
Nope. I had it like this and it didn't read anything at the end.

I put gcount after the read, and it's im.gcount()=2.700.008, if this helps
¿what are the values of `rows' and `cols'?

¿isn't ppm human readable?
Last edited on

ne555 wrote:
¿isn't ppm human readable?
The version he's using, P6, is binary.

I haven't tested your code, but this seemed to work in my limited testing (the binary data appears the same)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

int main()
{
    std::ifstream ifs("house_2.ppm",std::ios::binary);
    std::string t;
    ifs >> t;
    if (t != "P6") return 1;

    int w{}, h{};
    ifs >> w >> h;

    int maxcolor{};
    ifs >> maxcolor;

    std::vector<char> data(w * h * 3);
    ifs.read(&data[0], data.size());
    data.shrink_to_fit();

    std::cout << data.size() << std::endl;

    std::ofstream ofs("test.ppm", std::ios::binary);
    ofs.write(&data[0], data.size());
}
Last edited on
Topic archived. No new replies allowed.