Dynamically creating a char array to pass into fopen() function

zazas321
Posts: 231
Joined: Mon Feb 01, 2021 9:41 am

Dynamically creating a char array to pass into fopen() function

Postby zazas321 » Thu Aug 26, 2021 9:27 am

Hello. I am now working with SPIFFS and have the following function to open some file in my SPIFFS file system.

Code: Select all

static void read_hello_txt(char* file_name)
{
    ESP_LOGI(TAG, "Reading hello.txt");

    // Open for reading hello.txt
    
    char file_location[30];
    memset(file_location, 0, sizeof(file_location));
    strcat(file_location,"/spiffs/");
    strcat(file_location,file_name);
    printf("file location = %s \n",file_location);


    FILE* f = fopen("/spiffs/hello.txt", "r");
    //FILE* f = fopen(file_name, "r");
    if (f == NULL) {
        ESP_LOGE(TAG, "Failed to open hello.txt");
        return;
    }

    char buf[64];
    memset(buf, 0, sizeof(buf));
    fread(buf, 1, sizeof(buf), f);
    fclose(f);

    // Display the read contents from the file
    ESP_LOGI(TAG, "Read from hello.txt: %s", buf);
}
In order to open the file, the following function is being used:

Code: Select all

FILE* f = fopen("/spiffs/hello.txt", "r");
However, that is not good for me, Ideally, I would like to pass a char* into the function and then the function will decide which file to open because I am going to have many different files in there.

I have wrote some code that would create a string based on what I pass to the function

Code: Select all

    char file_location[30]; // create temporary char array to store the final file location
    memset(file_location, 0, sizeof(file_location)); // ensure that memory is clear
    strcat(file_location,"/spiffs/"); // append /spiffs/ to the string
    strcat(file_location,file_name); // append the name that is passed as a variable
    printf("file location = %s \n",file_location);
    FILE* f = fopen(file_name, "r");
I have tried to print the string that I have created and it look alright, see the serial monitor:

Code: Select all

file location = /spiffs/hello.txt
E (365) example: Failed to open hello.txt
As you can see, it prints out exactly the same as I would if I hardcode the file location to the function but does not work

Code: Select all

FILE* f = fopen("/spiffs/hello.txt", "r");
Could someone suggest me what could be wrong here?

davidzuhn
Posts: 17
Joined: Fri Sep 20, 2019 1:50 am

Re: Dynamically creating a char array to pass into fopen() function

Postby davidzuhn » Thu Aug 26, 2021 4:28 pm

You're doing the work to build a string in file_location, printing it from file_location, and then opening file_name (which isn't the full path).

Who is online

Users browsing this forum: Baidu [Spider] and 162 guests