簡體   English   中英

C-打開文件並通過傳遞文件指針作為參數逐字符讀取char

[英]C - Opening a file and reading char by char with passing the file pointer as argument

我在理解何時應該傳遞指針以及指針指向的東西時遇到了麻煩。 在我的代碼中:

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)

我知道這里有很多問題,但是我不知道什么是正確的:1.我是否打開正確的論點? 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. 我在使用正確的指針嗎?

唷! 因此, 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM