1

I'm trying to pass the name of a text file to two different functions so that they can operate on the file separately. The first loop works fine and produces the result that I expect, but the second function gets stuck in an infinite loop. Here is the main function:

#include <stdio.h>
#include <stdlib.h>
int countCharacters(const char *nameOfFile);
int countWords(const char *nameOfFile);
int main()
{
    int characterCount = 0;
    int wordCount = 0;

    char fileName[100];

    printf("Enter the name of the text file: ");
    scanf("%s",fileName);

    characterCount = countCharacters(fileName);
    wordCount = countWords(fileName);

    printf("Characters:%d  \n",characterCount );
    printf("Words:%d  \n",wordCount);

    return 0;
}

This is the first function:

#include <stdio.h>
#include <stdlib.h>
int countCharacters(const char *nameOfFile)
{
        char currentCharacter;
        int numCharacter = 0;
        FILE *fpt;

        fpt = fopen(nameOfFile,"r");

        while( (currentCharacter = fgetc(fpt)) != EOF )
        {
            if(currentCharacter != ' ' && currentCharacter != '\n')
                numCharacter++;
        }
        fclose(nameOfFile);
        return numCharacter;
}

And this is the second function:

#include <stdio.h>
#include <stdlib.h>
int countWords(const char *nameOfFile)
{
        char currentCharacter;
        int numWord = 0;
        FILE *fpt;

        fpt = fopen(nameOfFile,"r");

        while( (currentCharacter = fgetc(fpt)) != EOF )
        {
            if(currentCharacter == ' ' || currentCharacter == '\n')
                numWord++;
        }
        fclose(nameOfFile);
        return numWord;
}

So my question is, how does C deal with the name of a file that has been passed to two different functions, and what should I do to prevent infinite loops like this from happening when I want to use the name of a text file in more than one function? I made sure that fpt pointed to the beginning of the text file when it was opened in both instances, and I don't see what the problem is with the loop to g through the file, since the two have identicle conditions.

Marco Aiello
  • 179
  • 10

2 Answers2

0

Corrected code on repl.it

Replace fclose(nameOfFile) with fclose(fpt)

From cppreference.com,

*FILE *fopen( const char *filename, const char *mode );*

If successful, returns a pointer to the new file stream, shortly a handle for opened file.

If you will need to reset to the start of the file, you could use rewind(*FILE stream)

rewind(fpt)
P47 R1ck
  • 148
  • 1
  • 12
0

Should always close the file with the FILE pointer.

FILE *fp = fopen(filename, w) ;

fclose(fp) ;