如何通过提供文件指针和文件名来打开函数内的文件 [英] How to open a file inside a function by providing the file pointer and the filename

查看:109
本文介绍了如何通过提供文件指针和文件名来打开函数内的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int openfile(FILE **fp,char filename[])
{
    char ch;
    fp = fopen(filename,"r");
    while( (ch = fgetc(fp)) != EOF )
    {
        printf("%c",ch);
    }
    return 0;
}

int main()
{
    FILE *fp;
    
    openfile(&fp,"abc.txt");

    fclose(fp); 

    return 0;
}



这是从函数打开文件的正确方法吗?


Is this a correct way to open a file from a function ?

推荐答案

这取决于你想要做什么。但是,文件指针在函数内部更为明智。此外, openfile 作为名称有点模棱两可,因为该函数会打开并处理该文件;它为什么不关闭呢?

更好的结构是将文件名只发送到函数中,让它返回文件指针。然后,您可以将该指针传递给其他函数来处理该文件。或者,您的函数可以打开文件,将文件中的所有数据读入内存缓冲区或对象集,关闭文件,然后返回内存。
It depends what you are trying to do. However, it would be more sensible for the file pointer to be internal to the function. Also openfile is a bit ambiguous as a name since the function opens and processes the file; why does it not also close it?
A better structure would be to send just the filename into the function, and let it return the file pointer. You can then pass that pointer to other functions to process the file. Alternatively, your function could open the file, read all the data from the file into a memory buffer or set of objects, close the file, and just return the memory.


这篇关于如何通过提供文件指针和文件名来打开函数内的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆