跳到主要内容

写数据到文件(调试用)

只保存 16 个打开的文件句柄,所以只是调试时存文件用的:

static int temp_save_file(char *filename, u8 *data, int len, int need_stop)
{
static char filename_list[16][256] = {0};
static int opened_file_fds[sizeof(filename_list)/sizeof(filename_list[0])] = {-1};
int isFileOpened = -1;
for (int i = 0; i < sizeof(filename_list)/sizeof(filename_list[0]); i++)
{
if (0 == strcmp(filename_list[i], filename))
{
isFileOpened = i;
break;
}
}

if (need_stop)
{
if (isFileOpened!= -1)
{
printf("[snippet] remove fd %d filename %s\n",
opened_file_fds[isFileOpened], filename_list[isFileOpened]);
close(opened_file_fds[isFileOpened]);
filename_list[isFileOpened][0] = '\0';
opened_file_fds[isFileOpened] = -1;
}
return 0;
}

// 如果文件已经打开,直接使用已打开的文件描述符进行写入操作
if (isFileOpened!= -1)
{
int fd = opened_file_fds[isFileOpened];
ssize_t written = write(fd, data, len);
if (written!= len)
{
printf("[snippet] write error\n");
return -1;
}
return 0;
}

// 检查是否还有空位置
int freeIndex = -1;
for (int i = 0; i < sizeof(filename_list)/sizeof(filename_list[0]); i++)
{
if (strlen(filename_list[i]) == 0)
{
freeIndex = i;
break;
}
}

if (freeIndex == -1)
{
printf("[snippet] no free space\n");
return -1;
}

// 存储文件描述符和文件名
int fp = open(filename, O_APPEND | O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
if (fp == -1)
{
return -1;
}
printf("[snippet] add fd %d filename %s\n", fp, filename);
opened_file_fds[freeIndex] = fp;
strncpy(filename_list[freeIndex], filename, 255);

// 写入数据
ssize_t written = write(fp, data, len);
if (written!= len)
{
printf("[snippet] write error\n");
return -1;
}
return 0;
}

使用方法:

temp_save_file("/var/rec/c1/radioA.raw", audio_frame.data, audio_frame.len, !global_enable_save_audio);
handle(audio_frame);
temp_save_file("/var/rec/c1/radioB.raw", audio_frame.data, audio_frame.len, !global_enable_save_audio);