c - 尝试在函数中使用 txt 文件时获取 "invalid type argument of ' ->' (have ' int')"

标签 c function pointers int

我必须获取我为打开 txt 文件并计算函数中的单词数而编写的代码,但在正确移动文本文件时遇到问题(我很确定)。

我尝试过谷歌搜索如何在c中返回文件,显然是这个错误,并且在尝试和错误后我遇到了一些关于一元无效类型参数的错误。我不擅长编程,但在切换到不同的电气工程路径之前,我必须完成一些编程作业以进行签核,尤其是这个作业,我遇到了很多麻烦。

#include <stdio.h>
#include <stdlib.h>

char openIt();
int countIt(char (*p_file));

int main()
{
    int wordCount = countIt(openIt());
}

char openIt(void)
{
    FILE * p_file = fopen("alice-ch1.txt", "r");
    return p_file;
}

int countIt(char (*p_file))
{
    int wordcount = 0;
    int i = 0;

    if (p_file == NULL)
    {
        printf("File cannot be opened!\n");
    }
    else
    {
        char tempChar;
        char chapter[16383];
        int i;
        int wordcount = 0;
        int filed = fgetc(p_file);
        while (!feof(*p_file))   //this is where the error occurs
        {
            for(i = 0; !feof(*p_file); i++)
            {
                tempChar = getc(p_file);
                chapter[i] = tempChar;

                if(chapter[i] == ' ' || chapter[i] == '\n')
                {
                    if((chapter[i-1] != ' ' || chapter[i-2] != ' ') && chapter[i-1] != '*' && chapter[i-1] != '\n')
                    {
                        wordcount++;   // ((chapter[i-1] <= 'A' && chapter[i-1] >= 'Z') || (chapter[i-1] <= 'a' && chapter[i-1] >= 'z'))
                    }
                }
            }

        }
        fclose(p_file);
    }
}

我希望它能够计算给定文本文件中的单词数,但我从标题中收到错误消息

最佳答案

此函数的返回类型错误

char openIt(void)
{
    FILE * p_file = fopen("alice-ch1.txt", "r");
    return p_file;
}

p_file 是指向 FILE (FILE *) 的指针,因此它也应该是用作返回值的数据类型。

然后您将该函数的返回值传递给 countIt...但这并不需要 FILE *,因为它也是唯一的参数。这正是对文件进行操作的各种函数(即fgetc)所期望的。这就是您的问题所指的特定错误的来源,因为您取消引用 p_file 因此它不再是指针。

如果您的编译器没有使用此类代码抛出大量错误和警告,我会感到非常惊讶。

您应该将函数定义更改为如下。

FILE *openIt(void)

int countIt(FILE *p_file)

关于c - 尝试在函数中使用 txt 文件时获取 "invalid type argument of ' ->' (have ' int')",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57187508/

相关文章:

c - 如何修复此代码(使用 c 中的 char 将二进制转换为十进制)?

vb.net - 如何从VB.net轻松调用IronPython函数?

c - 将分配的内存视为不同类型

c++ - 如何 cudaMemcpy __device__ 初始化的 var

c - 平均函数返回 nan

C 嵌套宏

python - 将头文件 #ifndef 添加到当前目录下的 C 头文件中

c++ - 从函数返回数组或多个变量

python - Python中的函数和C++中的函数有什么区别?

c - 防止本地指针