Click here to Skip to main content
11,413,961 members (76,648 online)
Rate this: bad
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 )
    return 0;
int main()
    FILE *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

1 solution

Rate this: bad
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.

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

  Print Answers RSS
0 OriginalGriff 379
1 Maciej Los 210
2 Sascha Lefévre 175
3 Kornfeld Eliyahu Peter 170
4 KARTHIK Bangalore 145
0 Sergey Alexandrovich Kryukov 9,035
1 OriginalGriff 7,387
2 Maciej Los 3,640
3 Abhinav S 3,298
4 Peter Leow 3,084

Advertise | Privacy | Mobile
Web01 | 2.8.150427.2 | Last Updated 30 Jan 2013
Copyright © CodeProject, 1999-2015
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