0

Hey guys,

I a new CS student taking a class on C and I have a question about passing by reference.

I have a problem in which I am trying to open a file called reportFile. The problem is that when I try to do this using a function, as my prof wants, I keep getting told that there is some sort of conversion error. I'm a little stuck and I was hoping the forum could help answer the question...

For reference, here are some relevant bits of code...

//Function Prototype
void OpenReportFile(FILE *reportFile);

//Variable Declaration
FILE *reportFile

//Use in main
OpenReportFile(reportFile);

//Function
void OpenReportFile(FILE *reportFile)
{
    reportFile = fopen("c:\\temp\\report.txt","wt");
    if (reportFile == NULL)
    {
        printf("Report file open request failed.\n");
        printf("Press any key to exit...\n");
        fflush(stdin);
        getchar();
        exit(-10);
    }
}

I appreciate any help you guys can give me. Thanks!!!

Edited by mike_2000_17: Fixed formatting

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by snprime
0

If you are calling that from some other function then expect to use the open file handle after that function returns, then the FILE pointer must be passed by reference. What you have coded is passing by value.

void OpenReportFile(FILE **reportFile)
{
*reportFile = fopen("c:\\temp\\report.txt","wt");
if (*reportFile == NULL)
{
    printf("Report file open request failed.\n");
    printf("Press any key to exit...\n");
    /* fflush(stdin);*/ <<<< BAD BAD BAD!!!
    getchar();
    exit(-10);
}
}

int main()
{
    FILE* infile = NULL;
    OpenReportFile( &infile );
    // Now you can use infile 
    fclose(infile);
}

Edited by Ancient Dragon: n/a

0

Thank you, Ancient Dragon! That worked perfectly. I really appreciate the help.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.