Iva
Iva

Reputation: 367

C read file with pointer to string as name

I have a dummy function char * getFileName() that just returns a pointer to an array of chars:

char * getFileName () {
    char buff[11] = "index.html";
    char *p;
    p = buff;
    printf ("name of the file: %s\n", p);
    return p;
}

In my case this pointer is the name is the name of a file I want to open and read from main:

int main() {
    char *fp;
    FILE *file;
    fp = getFileName();
    int c;
    file = fopen(fp, "r");
    if (file) {
        while ((c = getc(file)) != EOF) {
            putchar(c);
        }    
        fclose(file);
    }
    return (0);
}

However, I can't open that file using the pointer value as a name, although when I print fp, I get the correct name if the file: index.html. Any suggestions what I could be missing? Thank you :)

Upvotes: 0

Views: 1662

Answers (1)

Filipe Gonçalves
Filipe Gonçalves

Reputation: 21213

You are returning a pointer to a local variable - by the time getFileName() returns, buff is destroyed and the value of p points to memory that is no longer usable.

If you really want to do this, you must make buff a static variable:

char *getFileName(void) {
    static char buff[] = "index.html";
    char *p;
    p = buff;
    printf ("name of the file: %s\n", p);
    return p;
}

static variables are not stack-allocated; they are.. well.. statically allocated.

A couple of other important details:

  • A function f that doesn't receive any arguments should be declared as f(void).
  • In this case, you don't have to explicitly write out the size of buff, because you initialized it with "index.html".

Upvotes: 1

Related Questions