Page 1 of 1

[Solved] How can I open the same file twice? not the same behaviour as on windows..

Posted: Thu Nov 07, 2019 5:39 pm
by gunar.kroeger
How can I open the same file once to write a log continuously, and second to read it and upload it through wifi.

I wish to have 2 cursors moving on the file, and not have to fseek back and forth to impelement this feature.

I tested this code with esp-idf-v3.3 and on windows with CodeBlocks

Code: Select all

int main(int argc, char *argv[])
{
    printf("open\n");

    FILE *w = fopen("logtest.txt", "w");

	printf("read open = %x\n", w);
	if(!w)
		return 0;

	fprintf(w, "aaaa");
    fflush(w);
    //fsync(fileno(w));
	FILE *r = fopen("logtest.txt", "r");

	printf("read open = %x\n", r);
	if(!r)
		return 0;
	printf(".%c", fgetc(r));
	printf(".%c", fgetc(r));
	printf(".%c\n", fgetc(r));

	fprintf(w, "bbbb");
    fflush(w);
    //fsync(fileno(w));

	printf(".%c", fgetc(r));
	printf(".%c", fgetc(r));
	printf(".%c", fgetc(r));
	printf(".%c", fgetc(r));
	printf(".%c", fgetc(r));
	printf(".%c", fgetc(r));

        return 1;
    }
 
codeblocks works as expected, but with esp-idf with sdcard using FAT the second fopen call returns NULL.
Is there any flag I have to set or compiler option to make this code work? I've tried with w+ and r+ but got the same result.

Re: How can I open the same file twice? not the same behaviour as on windows..

Posted: Mon Nov 18, 2019 2:14 pm
by gunar.kroeger
should I report this as a bug?

Re: How can I open the same file twice? not the same behaviour as on windows..

Posted: Tue Nov 19, 2019 11:09 pm
by ESP_Angus
Hi gunar,

This is a limitation of the FatFs library that we use. Set this config option to 2 and you should be able to have the same file open twice:

https://docs.espressif.com/projects/esp ... fs-fs-lock

Note that this comes at a tradeoff of memory usage and efficiency (still relatively low cost compared to ESP32's available resources, though.)

Angus