Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
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:27am
Edited 30-Jan-13 4:32am
v2

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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
0 OriginalGriff 530
1 Sergey Alexandrovich Kryukov 340
2 BillWoodruff 259
3 PIEBALDconsult 230
4 CPallini 220
0 Sergey Alexandrovich Kryukov 10,615
1 Maciej Los 5,354
2 OriginalGriff 5,254
3 CPallini 3,719
4 BillWoodruff 3,476


Advertise | Privacy | Mobile
Web01 | 2.8.141029.1 | Last Updated 30 Jan 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100