Return FILE pointer from function and work on it on main

10,256

Solution 1

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

Solution 2

You seem to be treating warnings as errors here. I think you should first check the returned value for NULL to silence this error:

FILE *p_txt = create_file();

if (! p_txt) {
    fprintf(stderr, "[!] Failed to open the file!\n");
    return 1;
} else {
    fprintf(p_txt, "%s\n\n\n%s", "gggg", "lklf");
}

Also, when you're entering into if (!regularTxt), you're returning one from a function returning a pointer. Better return NULL instead.

Share:
10,256
mikel bubi
Author by

mikel bubi

Updated on June 17, 2022

Comments

  • mikel bubi
    mikel bubi almost 2 years

    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

  • Andrew Henle
    Andrew Henle almost 8 years
    nullptr is C++, not C.
  • Brad
    Brad almost 8 years
    @AndrewHenle Correct, fixed. (Habit)
  • Jonathan Leffler
    Jonathan Leffler almost 8 years
    Interestingly, in create_file(), you could move the return regularTxt; out of the if statement and use it in place of the return NULL; — simply return its value, NULL or not, but don't use it unless it is non-null.
  • Brad
    Brad almost 8 years
    @JonathanLeffler - True but my goal was to transform the code as directly from the original as possible to make it easier to follow for OP.
  • Jonathan Leffler
    Jonathan Leffler almost 8 years
    What's with the 1 == 2 comparison?