Function call to main

Asked by At

The objective is to display the word in "file.txt" that's between "} {". It runs when i write it in main() , but when I create a new funtion, and call that one in the main, it runs the code, but only to display nothing afterwords.

void listagem() {

    FILE *fp;
    char s[20],*l;

    fp = fopen("file.txt","r+");

    while((*l = fgetc(fp)) != EOF)
            if (strcmp(l,"}") == 0)
                fscanf(fp,"%[^{]", s);
                printf("%s", s);


int main() {


The file has "We are }in{ 2019." written, so it should display "in" after running it,but it only does so when I run the code directly in "main()". When trying to run it in "listagem()" and then calling it in "main()", it displays nothing after running the program.

1 Answers

Pierce On

You've declared l as a char pointer, but you never allocate memory for it.

char *l = malloc(sizeof(*l));
if(l == NULL){
   printf("Could not allocate memory for character buffer.\n");

Make sure that you free(l); at the end of your function, as well.

You probably want to add a newline (\n) to your printf() as well.