Search code examples
cprintffopenncursesfgetc

How to load 2D char array from file and print it with mvprintw() in C using ncurses.h?


I'm coding a small game and i decided to load a map from the file but I'm facing a problem.The file looks like this :

enter image description here

and i need to print it like it is in the file expect of dots. They has to be spaces. my code for print looks like this :

void printmap(){
    clear();
    refresh();
    FILE *mapfile;
    int width=30;
    int height=20;
    char map[20][30];
    mapfile = fopen(mapname, "r+");
        for (int row = 0; row < height; row++) {
            for (int col = 0; col < width; col++) {
                mvprintw(0,0,"             ");
                mvprintw(0,0,"%d %d",row,col);
                refresh();
                map[row][col]=fgetc(mapfile);
            }
        }
    fclose(mapfile);
    
    offsetW=(xMax-width)/2;
    offsetY=((yMax-height)/2)-3;
    printOffsetW = offsetW+23;
    printOffsetY = offsetY+17;
        
        for(int i=0;i<20;i++){
        offsetW=(xMax-width)/2;
        
        for(int y=0;y<width;y++){
            if(map[i][y]=='#'){
                attron(COLOR_PAIR(1));
                mvprintw(i,y,"#");
                attroff(COLOR_PAIR(1));
            }
            else if(map[i][y]=='*'){
                attron(COLOR_PAIR(2));
                mvprintw(i,y,"*");
                attroff(COLOR_PAIR(2));
            }
            else if(map[i][y]==' '||map[i][y]=='.'){
                mvprintw(i,y," ");
            }
            
            offsetW++;
        }
        offsetY++;
    }
   
    mvprintw(printOffsetY,printOffsetW,"@");
    refresh();
}

Offsets are there just for centering the map (in the future), so you can ignore them.

My actual print looks like this :

enter image description here

And I can't really tell, where the problem is.

I would appreciate any help. THANK YOU


Solution

  • As the map file includes newline character at the end of lines, each line contains width + 1 characters. Then the sequential fgetc() reads extra byte for each line and causes the skew in the vertical alignment.

    A workaround will be to explicitly read the newline character such as:

    for (int row = 0; row < height; row++) {
        for (int col = 0; col < width; col++) {
            ...
            map[row][col]=fgetc(mapfile);
        }
        fgetc(mapfile);                 // read the newline character and discard
    }
    

    Or more portable way:

    char map[20][30];
    char buf[BUFSIZ];                   // line buffer
    mapfile = fopen(mapname, "r+");
    for (int row = 0; row < height; row++) {
        fgets(buf, BUFSIZ, mapfile);    // read each line
        for (int col = 0; col < width; col++) {
            ...
            map[row][col]=buf[col];     // assign column values of the line
        }
    }