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!!!

Recommended Answers

All 2 Replies

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);
}

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.