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 5:27am
Edited 30-Jan-13 5: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 DamithSL 320
1 OriginalGriff 195
2 Afzaal Ahmad Zeeshan 154
3 Zoltán Zörgő 149
4 Peter Leow 115
0 OriginalGriff 7,510
1 DamithSL 5,519
2 Sergey Alexandrovich Kryukov 4,994
3 Maciej Los 4,936
4 Kornfeld Eliyahu Peter 4,514


Advertise | Privacy | Mobile
Web03 | 2.8.141223.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