Click here to Skip to main content
Sign Up to vote bad
good
See more: C++C
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 ?
Posted 30 Jan '13 - 4:27
Edited 30 Jan '13 - 4:32


1 solution

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.
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 Arun Vasu 339
1 OriginalGriff 320
2 Sergey Alexandrovich Kryukov 315
3 Tadit Dash 221
4 CPallini 178
0 Sergey Alexandrovich Kryukov 9,955
1 OriginalGriff 7,589
2 CPallini 4,028
3 Rohan Leuva 3,422
4 Maciej Los 2,949


Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 30 Jan 2013
Copyright © CodeProject, 1999-2013
All Rights Reserved. Terms of Use
Layout: fixed | fluid