Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return FILE pointer from function and work on it on main

Tags:

c

file

pointers

I've tried to return a FILE pointer from some function to main(). After it, I've tried to do some fprintf on the pointer but it wasn't working. Here is my code:

My function:

FILE *create_file(void){

    FILE *regularTxt = NULL;
    regularTxt = fopen("MyLogExamplekkggggggk.txt", "wt");
    if (!regularTxt){
        printf("error with regtxt");
        getchar();
        return 1;
    }
    char first_part_string[] = "kkkkik";
    fprintf(regularTxt, "%s\n\n\n%s", "ttttg", "lklf");
    return regularTxt;
}

The main function:

int main(void)
{
    p_txt = create_file();
    fprintf(p_txt, "%s\n\n\n%s", "gggg", "lklf");
    return 0;
}

The error:

Error 92 error C4703: potentially uninitialized local pointer variable 'p_txt' used

like image 995
mikel bubi Avatar asked Oct 19 '22 08:10

mikel bubi


1 Answers

Without all the code I can't explain the warning, but when you "return 1" from the function in the error case you didn't initialize the pointer correctly.

Change to this:

#include <stdio.h>
#include <stdlib.h>

FILE *create_file()
{
    FILE *regularTxt = NULL;
    regularTxt = fopen("MyLogExamplekkggggggk.txt", "wt");
    if (regularTxt) {
        char first_part_string[] = "kkkkik";
        fprintf(regularTxt, "%s\n\n\n%s", "ttttg", "lklf");
        return regularTxt;
    }
    return NULL; // error
}

int main(void)
{
    FILE* p_txt = create_file();
    if (p_txt == NULL)
    {
        printf("error with file");
        getchar();
        exit(1); // quit
    }
    fprintf(p_txt, "%s\n\n\n%s", "gggg", "lklf");
    return 0;
}
like image 162
Brad Avatar answered Nov 15 '22 03:11

Brad