【问题标题】:How to pass file pointer to a function in c如何将文件指针传递给c中的函数
【发布时间】:2021-07-07 10:52:03
【问题描述】:

我想将文件指针作为参数传递给视图函数。然后我想从视图函数中获取输出文件中的数据。但是每次都告诉我找不到文件。

#include<stdio.h>
void view(FILE *file){
    char c;
    file=fopen(file,"r");
    if(file==NULL){
        printf("file not found");
    }
    else{
        while(!feof(file)){
       c=fgetc(file);
       printf("%c",c);
    }
    fclose(file);
}
    }



int main(){

FILE *file;
file=fopen("hello.txt","w");
char s[]="hello world";

fprintf(file,"%s",s);
fclose(file);
printf("Enter 1 to read file");
int n;
scanf("%d",&n);
if(n==1)
view(file);

return 0;

}

【问题讨论】:

  • 编译器不会对你大喊大叫吗?因为多想一下在view 中对fopen 的调用:file=fopen(file,"r")FILE * 作为文件名传递给fopen 真的有意义吗?编译器真的应该抱怨这一点。
  • 关于一些不相关的注释,请阅读 Why is “while ( !feof (file) )” always wrong? 并记住 fgetc 返回一个 int,这对于与 EOF 的比较很重要你应该有而不是feof
  • All the big three compilers 发出警告。您应该始终将警告视为必须修复的错误。如果您真的没有收到任何警告,那么您使用的是什么编译器?什么版本的?
  • 如果在调用之前关闭文件,为什么要传递FILE 指针?指向文件的指针在关闭后不得用于任何操作。通过它是没有价值的。您应该改为传递文件名。
  • 是的,你可以,但这对你代码中的问题没有帮助。也许您打算将文件 name 作为参数传递?那么参数变量应该被命名为不同的名称,而是使用const char * 类型。而且你需要在函数本身中定义FILE *file(全局变量不好)。

标签: c function file pointers


【解决方案1】:

正如 cmets 中已经说明的,在这个 answer 中,fopen 参数是错误的,当你应该传递文件路径时,你传递了一个指向文件的指针。

除此之外,您可以重构代码,这样您就不必关闭并重新打开文件:

void view(FILE *file)
{
    // the file is already opened, no need to reopen it
    int c;
   
    while ((c = fgetc(file)) != EOF) // better read routine
    {                                // you could also use fgets to read the whole line
        printf("%c", c);
    }
    fclose(file);
}
int main()
{
    FILE *file;
    file = fopen("hello.txt", "w+"); // open to write and read
    int n;
    char s[] = "hello world";

    if (file == NULL)
    {
        printf("file not found"); // perror("fopen"); would be better
        return EXIT_FAILURE; // #include <stdlib.h>
    }

    fprintf(file, "%s", s);

    printf("Enter 1 to read file: ");

    if (scanf("%d", &n) == 1)
    {       
        if (n == 1)
        {
            rewind(file); // reset file pointer offset to the beginning
            view(file);
        }
    }
}

【讨论】:

    【解决方案2】:

    你的错误在这里:

    file=fopen(file,"r");
    

    使用这样的东西:

    file=fopen("file name","r");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-12
      • 2011-05-19
      • 1970-01-01
      • 2012-02-22
      • 2010-10-02
      相关资源
      最近更新 更多