Question

I need to scan a file for letters to form a scrambled word. Everything looks okay but the debugger doesnt execute the command. Any advice would be greatly appreciated.

Code:

void playGame(char array1[SIZE], FILE*aPtr)    
{

    aPtr = fopen("words.txt", "r");
    int i;
    for (i = 0; i < SIZE; i++){
        fscanf(aPtr, " %c", array1[i]);
        printf("%c", array1[i]);
    }
}

Heres how I call the function in main

playGame(&scramble[SIZE], inPtr);

the array scramble[] is declared as is the FILE*inPtr, Also, SIZE is defined as 10.

Was it helpful?

Solution

In your calling code, you have:

FILE *fp = 0;
char game[SIZE];

Given that you're opening the file in the function, but not closing it, you need to change the file in the function, so the call could be:

playGame(game, &fp);
if (fp != 0)
    fclose(fp);

But the function should be changed to:

void playGame(char array1[SIZE], FILE **aPtr)    
{
    FILE *fp = fopen("words.txt", "r");
    if (fp != 0)
    {
        *aPtr = fp;
        ...other code...
    }
}

Alternatively, the file should be opened and closed in the calling code and the file pointer simply passed to playGame():

FILE *fp = fopen("words.txt", "r");
if (fp != 0)
{
    playGame(game, fp);
    fclose(fp);
}

With this interface, there is no fopen() (or fclose()) call in playGame(), which keeps its current interface (void playGame(char game[SIZE], FILE *fp)). This makes more sense. Very often it is correct for the function that opens a file to be responsible for closing it too. There are exceptions, but not all that many of them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top