C - 打开文件并通过将文件指针作为参数传递来读取char的char

时间:2016-08-09 09:12:41

标签: c file stream

我无法理解何时应该传递指针以及它指向的东西。在我的代码中:

int checkFile(FILE fp)
{
int c;
while((c = fgetc(*fp)) != EOF)
{
    putchar(c);
}
fclose(*fp);

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

FILE *fp = fopen(argv[0], "r");
char fileName = argv[1];
if(argc > 2)
{
    printf("Please supply a file!\n");
    printf("usage: CheckParenthesis <file name>\n");
}
if (fp == NULL)
{
    printf("Error! trying to open the file\n");
    return 1;
}
else
{
    checkFile(fp);
}
return 0;
}

我在编译时遇到重大错误,错误是:

    C:\Users\Dell\ClionProjects\CheckParenthesis\CheckParenthesis.c: In          function 'checkFile':
C:\Users\Dell\ClionProjects\CheckParenthesis\CheckParenthesis.c:17:22: error:     invalid type argument of unary '*' (have 'FILE')
 while((c = fgetc(*fp)) != EOF)
                  ^
C:\Users\Dell\ClionProjects\CheckParenthesis\CheckParenthesis.c:21:12: error:     invalid type argument of unary '*' (have 'FILE')
 fclose(*fp);
        ^
C:\Users\Dell\ClionProjects\CheckParenthesis\CheckParenthesis.c: In function 'main':
C:\Users\Dell\ClionProjects\CheckParenthesis\CheckParenthesis.c:28:21: warning: initialization makes integer from pointer without a cast
 char fileName = argv[1];
                 ^
C:\Users\Dell\ClionProjects\CheckParenthesis\CheckParenthesis.c:41:9: error: incompatible type for argument 1 of 'checkFile'
     checkFile(fp);
     ^
C:\Users\Dell\ClionProjects\CheckParenthesis\CheckParenthesis.c:12:5: note:   expected 'FILE' but argument is of type 'struct FILE *'

int checkFile(FILE fp)

我知道这里有几个问题,但我不知道什么是正确的: 我打开正确的论点吗? argv [0]和argv [1]似乎都是我指定的文件路径。添加此作为打印输出我为获取argv信息: 测试:

    printf("There are %d args, %s, %s\n", argc,argv[0],argv[1]);

结果:

    There are 2 args,                    C:\Users\Dell\.CLion2016.2\system\cmake\generated\CheckParenthesis-    5dc89373\5dc89373\Release\CheckPare
nthesis.exe, C:\testing\brackets.txt
  1. 我正在使用正确的指针吗?

1 个答案:

答案 0 :(得分:2)

唷!所以checkfile()应该采用文件指针而不是文件。将int checkFile(FILE fp)更改为int checkFile(FILE* fp),然后稍后您应该将*fp更改为fp

您的代码应如下所示:

int checkFile(FILE* fp) {
    int c;
    while ((c = fgetc(fp)) != EOF) {
        putchar(c);
    }
    fclose(fp);
}

int main(int argc, char *argv[]) {
    FILE *fp = fopen(argv[0], "r");
    char* fileName = argv[1]; // thanks to dvhh in the comments
    if (argc > 2) {
        printf("Please supply a file!\n");
        printf("usage: CheckParenthesis <file name>\n");
    }
    if (fp == NULL) {
        printf("Error! trying to open the file\n");
        return 1;
    } else {
        checkFile(fp);
    }
    return 0;
}

这应该有帮助,我也可以看看你是如何编译的?(假设你正在使用gcc)