HELP:function at c returning (null)

Joined
Dec 22, 2023
Messages
34
Reaction score
5
i am rather new to c,and im trying to create a function that open a file,read a line,and return that line,but,on the part that open the file,it returns a warning,but if i take the same code and put directly into "int main()',it works,but then the function doesnt work,it returns null here is the code
C:
#include <stdio.h>
#include <stdlib.h>
/*
 * todo can be ->
 * 1 -> read
 * 2 -> wright
 * 3 -> overwright
 * WILL ADD MORE
*/
/*
 * mode can be ->
 * 0 -> none of the below
 * 1 -> read all lines
 * 2 -> read one line
 * WILL ADD MORE
*/


char *open_readF(char *filepath,const int mode,const int todo){
        FILE *file = fopen(filepath,"r");
        char result[100];
        fgets(result, 100, file);
        return result;
}
int main(){
    /*     
        here is the code that works,its the same,but it works somehow
    */
        FILE *file = fopen("addons.c","r");
        char result[100];
        fgets(result, 100, file);
        printf("CODE STRIPED FROM FUNCTION ->%s\n",result);
        char *var = open_readF("addons.c",0,1);
        printf("FUNCTION ->%s\n",var);
        return 0;
}
 
Joined
Dec 22, 2023
Messages
34
Reaction score
5
the only thing gcc says its that im returning a local variable,and probably thats the problem,but i tryed everything and it doesnt work!
 
Joined
Sep 21, 2022
Messages
122
Reaction score
15
High level languages like BASIC can have string return values.

C gives the programmer more control over the way memory is used.

Allocate memory in your main for a string, then pass down the string's address as an argument (pointer).

Don't return anything.

Just a suggestion.
 
Last edited:
Joined
Nov 24, 2022
Messages
80
Reaction score
7
Ale the fun about C is You don't need to use lines.

Take a look how I write date from lines to correct form of storage information, in C this exactly how should be done

 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,058
Latest member
QQXCharlot

Latest Threads

Top