fgets заставляет функцию пропустить до конца кода вместо того, чтобы работать должным образом. LOADS FILE AS NULL - PullRequest
0 голосов
/ 11 марта 2020

Я пытаюсь открыть файл, прочитать из него информацию и затем закрыть файл. В том же каталоге, что и код, находится .txt, который я хотел бы прочитать. Когда я компилирую, нет никаких предупреждений (и, очевидно, нет ошибок). Когда я go построчно в отладчике, он выходит с кодом в заголовке, но когда я запускаю его как обычно, он выходит с 0, как обычно, но ничего не печатается, как программа пропущена до конца. Операторы printf находятся в других функциях, и это единственная функция, которая обращается к файлу, поэтому нет других fgets, scanf и т. Д. c.

Я использую CLion, если это поможет. И весь код вне этой функции полностью протестирован. Он просто использовал stdin, и я хотел бы использовать fopen, потому что это единственная функция, которая нуждается в изменении.

Пример ввода в файле maze3.txt :

6 5
1 1 1 1 1
1 0 0 e 1
1 1 1 0 1
1 r 1 0 1
1 0 0 0 1
1 1 1 1 1

НОВАЯ ИНФОРМАЦИЯ: Почему файл загружается как NULL? Я не понимаю, что не так ... Кроме того, эта функция просто должна хранить ее в глобальном 2D-массиве, как есть, так что у вас есть все, что вам нужно попробовать сами сейчас

Для справки: это глобальные и полностью инициализирован.

лабиринт: двумерный массив символов

MAX_DIMENSION: финальная переменная int = 20;

Я пометил fgets и открыл с помощью ********* **************

Рассматриваемая функция - loadMaze (); вот минимальная версия для тестирования:

#define MAX_DIMENSION 20
char maze[MAX_DIMENSION][MAX_DIMENSION];
int mazeRows;
int mazeCols;

/*This is here to allow you to print the maze to see if it loaded correctly(it
should not have spaces or the 2 numbers from the first row of the input but
should match otherwise)
*/
void printMaze(){
    checkState();

    printf("\n");//space for ease of reading

    for (int r = 0; r < mazeRows; ++r) {
        for (int c = 0; c < mazeCols; ++c) {
            printf("%c ", maze[r][c]);
        }
        printf("\n");
    }
}

    //this function loads the maze by using the standard input of a text file with specific formatting
void loadMaze(){
    //file loading stuff
//********************************************************
    FILE * file = fopen("maze3.txt", "r");

    int lineLength = MAX_DIMENSION*2 + 2;//this will be able to store all 20 with a space after and between
    char string[lineLength];//this is the longest line that should be allowed as input with a bit of room for an accidental space

    //gets the rows AND cols count
//********************************************************
    fgets(string, lineLength, file);//THIS IS WHERE IS STOPS IF I AM GOING LINE BY LINE IN THE DEBUGGER

    mazeRows = (int)strtol(strtok(string, " "), NULL, 10);//takes the first token and extracts the integer value to set as the rows
    mazeCols = (int)strtol(strtok(NULL, " "), NULL, 10);//takes the second token and extracts the integer value to set as the cols

    //copies the maze into the arrays
    for (int r = 0; r < mazeRows; ++r) {
//********************************************************
        fgets(string, lineLength, file);

        maze[r][0] = strtok(string, " ")[0];//puts the first char in the maze
        for (int c = 1; c < mazeCols; ++c) {
            maze[r][c] = strtok(NULL, " ")[0];//puts the next char in the maze
        }
    }

    fclose(file);

    checkState();
}

int main(){
    loadMaze();
    printMaze();
}
...