sd file read to char*

what's the better way to get the content of a File type into char* ? the best I get is:

	const char* buffer;
	File bckFile = SD.open("backup/BACKUP.txt");
	if (!bckFile) Serial.println("FAIL TO LOAD BACKUP");
	while (bckFile.available()){
		buffer = bckFile.readString().c_str();
	}
	bckFile.close();

that code look like working but I wonder is there a better way.
I need the content in char array to use it in another library...

Thanks.

the best I get is

Aside from the use of the String class, what is wrong with that method?

You know how big the file is (bckFile.available() tells you that). You could use malloc() to allocate that much space (assuming that the file is small enough), and then use the read() method that takes an array and a size.

free() the memory when you are done with it.

Aside from the use of the String class, what is wrong with that method?

In term of simplicity and performance I wonder if there was a simple function that could do it directly that I didn't knew.

I don't know about malloc() and free() use, I will probably read about it. But I feel like it is a even more complicated solution.

So Thank's for your time Paul ! n happy new year.

Paul's suggestion is about as simple as it gets.
This is a similar thing to his suggestion, and works fine, (without using that horrible "String" class):-

    char* pBuffer;                              // Declare a pointer to your buffer.
    myFile = SD.open(F("fileName.txt"));        // Open file for reading.
    if (myFile)
    {
        unsigned int fileSize = myFile.size();  // Get the file size.
        pBuffer = (char*)malloc(fileSize + 1);  // Allocate memory for the file and a terminating null char.
        myFile.read(pBuffer, fileSize);         // Read the file into the buffer.
        pBuffer[fileSize] = '\0';               // Add the terminating null char.
        Serial.println(pBuffer);                // Print the file to the serial monitor.
        myFile.close();                         // Close the file.
    }
    // *** Use the buffer as needed here. ***
    free(pBuffer);                              // Free the memory that was used by the buffer.

You probably don't actually need an 'unsigned int' for the file size, but I was just making sure. If it's even bigger than that, use a larger variable, but it allows files up to 65535 bytes in length, (counting the terminating null character)..

1 Like

Yes thank.

Effectively pretty solution. will implement it.

In term of simplicity and performance I wonder if there was a simple function that could do it directly that I didn't knew.

that's what a was talking.. :stuck_out_tongue:

thank again !