将文本文件的名称传递给多个函数时发生无限循环

问题描述 投票:1回答:2

我正在尝试将文本文件的名称传递给两个不同的函数,以便它们可以分别对文件进行操作。第一个循环工作正常,并产生了我期望的结果,但是第二个函数陷入了无限循环。这是主要功能:

#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;
}

这是第一个功能:

#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;
}

这是第二个功能:

#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;
}

所以,我的问题是,C如何处理已传递给两个不同函数的文件的名称,当我想使用文本文件的名称时,我应该怎么做才能防止此类无限循环的发生在多个功能中?我确保在两个实例中打开fpt时都指向该文本文件的开头,并且由于两个文件具有相同的条件,因此我看不到循环遍历文件的问题是什么。

c function text-files
2个回答
0
投票

repl.it上的正确代码

fclose(fpt)替换fclose(nameOfFile)

来自cppreference.com

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

如果成功,则返回指向新文件流的指针,不久后将为打开文件的句柄。

如果需要重置为文件的开头,则可以使用rewind(*FILE stream)

rewind(fpt)

0
投票

应始终使用FILE指针关闭文件。

文件* fp = fopen(文件名,w);

fclose(fp);

© www.soinside.com 2019 - 2024. All rights reserved.