简体   繁体   中英

how to reading .raw file in c++

    void solution3(){
        char str[100];
        int height, width;

        printf("가로와 세로 길이를 입력 : ");
        scanf("%d %d", &width, &height);
        FILE* fp = fopen("lena_256x256.raw", "rb");

        //2dynimic
        unsigned char **p = new unsigned char*[height];

        for(int i = 0; i < height; i++) *(p + i) = new unsigned char[width];
        for(int i = 0; i < height; i++){
            for(int j = 0; j < width; j++)
                fread((void*)p[i][j], sizeof(unsigned char), height * width, fp);
        }

        //print
        for(int i = 0; i < height; i++){
            for(int j = 0; j < width; j++)
                printf("%4d ", p[i][j]);
        }

        //del dynimic
        for(int i = 0; i < height; i ++) delete[] p[i];
        delete[] p;

        fclose(fp);
    }

void main(){
 solution3();
}

Error message is "string != NULL" why cant read .raw file? and I try p[i][j] fix (void*)p[i][j] . but can not.

I want read .raw and print info about .raw light

The code has undefined behavior here:

  unsigned char **p = new unsigned char*[height]; .... fread((void*)p[i][j], sizeof(unsigned char), height * width, fp); 

p is a pointer to pointer of char. Which means that p[i][j] is a char, which the code casts to (void*) . This is an invalid address which fread tries to write to.

It is likely that you want:

    for(int i = 0; i < height; i++){
        if (fread((void*)p[i], 1, width, fp) != width)
        {
           manage the error condition
        }
    }

Aside of that, it is not recommended to work directly with new/delete, and std::vector would be safer in this case. Also, void main() is wrong and should be int main() instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM