I’m trying to write a file on SD card if it’s inserted into the kit. Otherwise, the file should be written to the current directory of the project.
I can write the file in the project’s directory without any problems.
However, when I try to write it on the inserted SD card, it returns Invalide argument
!
FILE* open_file(void)
{
char filename[40];
struct tm *timenow;
time_t now = time(NULL);
if(card_inserted())
{
// Write to a file in the SD card
if(!card_mounted())
{
system("mount /dev/mmcblk0p1 /media/sdcard/");
}
// Change directory from the project's dir to the SD card dir
chdir("/media/sdcard/");
}
timenow = gmtime(&now);
strftime(filename, sizeof(filename), "logs/data_%Y-%m-%d_%H:%M:%S.txt", timenow);
// Open a file to save the received data in (appending mode)
FILE *f = fopen(filename, "w");
if (f == NULL)
{
perror("Error opening file!n");
abort();
}
return f;
}
I tried changing the :
s into -
s in the file name. This caused the error to change to Input/output error
.
I also tried not to use chdir()
. Instead, to directly do the following:
strftime(filename, sizeof(filename), "/media/sdcard/logs/data_%Y-%m-%d_%H-%M-%S.txt", timenow);
This didn’t solve the problem -> Invalid argument
.
I’m sure that the SD card is mounted to /media/sdcard/
and I can create a file into it using the terminal without any problem.
What can cause this error and how to solve it?
UPDATE
I made sure that the SD card is correctly mounted before running the program. This didn’t solve the problem.
Besides, when I try to write the file into SD card with a normal name, and not the current data and time, it works without any problems!!
Following is my updated code:
FILE* open_file(void)
{
struct tm *timenow;
time_t now = time(NULL);
if(card_inserted() && write_to_card)
{
char *filename;
filename = "/media/sdcard/logs/data.txt";
FILE *f = fopen(filename, "w");
if (f == NULL)
pabort("Error opening file!n");
return f;
}
else
{
char filename[40];
timenow = gmtime(&now);
strftime(filename, sizeof(filename), "logs/data_%Y-%m-%d_%H:%M:%S.txt", timenow);
FILE *f = fopen(filename, "w");
if (f == NULL)
pabort("Error opening file!n");
return f;
}
}
Advertisement
Answer
The SD card is probably using a FAT/NTFS file system and filenames in a FAT/NTFS file system cannot contain the :
character (and a few others).
If you replace the :
in the format string by -
, then it should work also on the SD card.