Click here to Skip to main content
13,505,212 members
Rate this:
Please Sign up or sign in to vote.
See more:
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 4:27am
Updated 30-Jan-13 4: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
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web03 | 2.8.180417.1 | Last Updated 30 Jan 2013
Copyright © CodeProject, 1999-2018
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