Почему содержимое моего файла исчезает и как правильно читать из этого файла?

У меня есть программа connect 4, которая позволяет пользователю вводить количество строк / столбцов и длину соединения, необходимого для победы. Программа работает так, что в любой момент игры вы можете ввести "сохранить" вместо столбца, в котором вы хотите разместить свой игровой элемент, и настройки игры (num_rows, num_columns, length_to_win) будут записаны в файл с именем settings.текст

Я могу подтвердить, что это работает, и settings.txt содержит данные примерно так:

7 7 4

где каждый номер является настройкой, а после него есть пробел.

Теперь я пытаюсь прочитать эти целые числа и установить их равными соответствующим переменным в качестве начала моего (надеюсь, успешного) метода load-game; однако, когда я пытаюсь использовать fscanf способом, показанным в приведенном ниже коде, ничего не происходит... а когда я смотрю на settings.txt после этого, он пустой... почему это?

основной метод

int main (int argc, char *argv[]) { 

setvbuf(stdout, NULL, _IONBF, 0);
printf("Starting Game\n");  


// the default values for board size if no command line arguments are used
int index;
int num_rows = 7;
int num_columns = 7;
int length_to_win = 4;
FILE *fp = fopen("settings.txt", "r");


// this loop checks for command line arguments and sets game variables accordingly.
for(index = 0; index < argc; ++index) {

    if ( strncmp( argv[index], "-l", 5) == 0 ) {
      fscanf(fp, "%d %d %d", &num_rows, &num_columns, &length_to_win);
    }
    if ( strncmp( argv[index], "-h", 5) == 0 ) {
      num_rows =atoi(argv[index + 1]);
    }
    if ( strncmp( argv[index], "-height", 5) == 0 ) {
      num_rows =atoi(argv[index + 1]);
    }
    if ( strncmp( argv[index], "-w", 5) == 0 ) {
      num_columns = atoi(argv[index + 1]);
    }
    if ( strncmp( argv[index], "-width", 5) == 0 ) {
      num_columns = atoi(argv[index + 1]);
    }
    if ( strncmp( argv[index], "-s", 5) == 0 ) {
      num_rows = atoi(argv[index + 1]);
      num_columns = atoi(argv[index + 1]);
    }
    if ( strncmp( argv[index], "-square", 5) == 0 ) {
      num_rows = atoi(argv[index + 1]);
      num_columns = atoi(argv[index + 1]);
    }
    if ( strncmp( argv[index], "-c", 5) == 0 ) {
      length_to_win = atoi(argv[index + 1]);
    }
    if ( strncmp( argv[index], "-connect", 5) == 0 ) {
      length_to_win = atoi(argv[index + 1]);
    }
}



// these conditionals check for valid board size
if (num_rows <= 0 || num_columns <= 0 ){
    printf("%s\n","You entered a width or length that was invalid." );
}
if (length_to_win <= 0 || length_to_win > (num_rows - 1)) {
    printf("%s\n","You entered a winning length that was invalid." );
}


// this creates the board
int array[num_rows][num_columns];
initialize(num_rows, num_columns, array);
int answer;
int player = 0;

printf("%s\n", "*********************");
printf("%s\n", "   Starting Board   ");
printf("%s\n", "*********************");
puts("\n");
printBoard(num_rows, num_columns, array);
puts("\n");
printf("Player: %ds Turn\n", player + 1);  


/*Start game loop*/
while(1) {       

    // prompts the user to select which column they want their piece to be placed
    // -1 on the temp because the first column is technically 0 so if a player
    // wants to place their piece in column "1", it'll be placed at index[0] accordingly
    printf("%s\n", "Enter Column # To Place Token"); 
    int column;
    char temp[20];       
    scanf("%s", temp); 

    if (strncmp (temp, "save", 5) == 0){

        // this writes the game settings to a file
        int *rows = &num_rows;
        int *cols = &num_columns;
        int *len = &length_to_win;
        FILE *fp = fopen("settings.txt", "w+");
        fprintf(fp, "%d ", *rows);
        fprintf(fp, "%d ", *cols);
        fprintf(fp, "%d ", *len);
        printf("Game Saved\n");
        fclose(fp);

    }
    else {
        column = atoi(temp) - 1; 
    }

    if ((column < 0 || column > (num_columns - 1)) && (strncmp (temp, "save", 5) != 0) ) {
        printf("%s\n","You entered a column that was invalid. Please try again." );
        continue;
    }

    int attmpt = place_token(player, column, num_rows, num_columns, array);
    if (attmpt != 1 && (strncmp (temp, "save", 5) != 0)) {
        printf("%s\n","This row is already full. Please try again." );
        continue;
    }

    printf("%s\n", "************************");
    printf("%s\n", "      Board Updated     ");
    printf("%s\n", "************************");  
    puts("\n");  
    printBoard(num_rows, num_columns, array);
    puts("\n");




    if (checkFullBoard(num_rows, num_columns, array)) {
        printf("%s\n","This game is a tie. Thanks for Playing.\n");
        return 0;
    }

    // this if-statement will constantly be run while the game progresses, 
    // meaning that winner will be called at every turn and 
    // all of the win conditions will be checked until a winner is found
    int isWin = winner(num_rows, num_columns, length_to_win, array);
    if(isWin != -1) {
        char temp2[20];
        printf("Player: %d is the winner! Thanks for Playing.\n", isWin + 1);
        printf("Play again? (enter 'y' to continue)\n");
        scanf("%s", temp2);

        if (strncmp (temp2, "y", 5) == 0){
          initialize(num_rows, num_columns, array);
          printBoard(num_rows, num_columns, array);
        }
        else {
          printf("Game over, goodbye!\n");
          return 0;
        }
    }

    // if a winner is not found then this if/else will continue to switch
    // between players at the end of each turn
    if ((strncmp (temp, "save", 5) != 0)) {
        if (player == 1) {
          player = 0;
      }
        else {
            player = 1;
        }
    }

    printf("Player: %ds Turn\n", player +1);
} // end of while loop

return 0;
} // end of main

1 ответ

Как предложено silentboy, решением было заменить "w+" на "a".

Другие вопросы по тегам