Я хочу чтобы в файл добавлялись данные, но когда я открываю его, там только самая последняя строчка
/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  * @author
  *  
  * With version made by Kim Maksim 2024.
  * email: <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>
  *  
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "fatfs.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "CANSPI.h"
#include "string.h"
#include "stdio.h"

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
RTC_HandleTypeDef hrtc;

SPI_HandleTypeDef hspi2;

UART_HandleTypeDef huart4;

/* USER CODE BEGIN PV */
char trans_str[256] = {"Default"};
char ascii_str[9] = {"Default"};
char filename[20];
char dateTime[50];
uint8_t Rx = 100;
uCAN_MSG rxMessage;
int Number = {0};
int LineNow;
FRESULT fres;

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_SPI2_Init(void);
static void MX_UART4_Init(void);
static void MX_RTC_Init(void);
/* USER CODE BEGIN PFP */
void GetDateTime(char *buffer);
void TransformToASCII(char* buffer, uint8_t* data);
void print(char message[128]) {
	HAL_UART_Transmit(&huart4, (uint8_t *)message, strlen(message), 100);
}
void GetLog_filename(char *filename, int log_index) {
    snprintf(filename, 20, "%s%d%s", LOG_FILE_PREFIX, log_index, LOG_FILE_SUFFIX);
}

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

void SD_GetStat(void)
{
	DWORD free_clusters, free_sectors, total_sectors;
	FATFS* getFreeFs;

	fres = f_getfree("", &free_clusters, &getFreeFs);
	if (fres != FR_OK) {
		snprintf(trans_str, 128, "ERROR: GetFree (%i)\n", fres);
	    print(trans_str);
	    while(1);
	}
	//Formula comes from ChaN's documentation
	total_sectors = (getFreeFs->n_fatent - 2) * getFreeFs->csize;
	free_sectors = free_clusters * getFreeFs->csize;

    snprintf(trans_str, 128, "SD card stats:\n%10lu KiB total drive space.\n%10lu KiB available.\n", total_sectors / 2, free_sectors / 2);
    print(trans_str);
}

int SD_CountLines(FIL fil) {
    char buffer[256];
    UINT bytesRead;
    int line_count = 0;

    f_lseek(&fil, 0);
    while (1) {
        f_read(&fil, buffer, sizeof(buffer) - 1, &bytesRead);

        if (bytesRead == 0) break;

        buffer[bytesRead] = '\0';

        for (UINT i = 0; i < bytesRead; i++) {
            if (buffer[i] == '\n') {
                line_count++;
            }
        }
    }

    return line_count;
}

uint8_t SD_WriteLine(FIL fil, char line[128])
{
	char readBuf[128];

	strncpy((char*)readBuf, line, strlen(line));
	print(readBuf);
	UINT bytesWrote;
	fres = f_write(&fil, readBuf, strlen(line), &bytesWrote);
	if(fres != FR_OK) {
	 	snprintf(trans_str, 128, "ERROR: SD_WriteLine (%i)\n", fres);
	 	print(trans_str);
	   	return 1;
	}
	fres = f_sync(&fil);
	if (fres!= FR_OK) {
		snprintf(trans_str, 128, "ERROR: Synchronization (%i)\n", fres);
		print(trans_str);
	    return 1;
	}
	return 0;
}

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */
  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_SPI2_Init();
  MX_UART4_Init();
  MX_RTC_Init();
  MX_FATFS_Init();
  /* USER CODE BEGIN 2 */
  if (!CANSPI_Initialize())
  {
	print("ERROR: Initialize CANSPI\n");
    while(1) { }
  }
  print("OK: Initialization\n");

  FATFS FatFs;
  FIL fil;

  //Open the file system
  fres = f_mount(&FatFs, "", 1); //1=mount now
  if (fres != FR_OK) {
	  snprintf(trans_str, 128, "ERROR: Mount (%i)\n", fres);
	  print(trans_str);
	  while(1);
   }
  print("OK: Mount FS\n");

  // Find last LOG
  fres = f_open(&fil, "log0.csv", FA_READ | FA_OPEN_EXISTING);
  if (fres == FR_OK)
  {
	  f_close(&fil);
	  print("OK: Find 'log0.csv'\n");
	  while (1)
	  {
		  GetLog_filename(filename, Number);
		  fres = f_open(&fil, filename, FA_READ | FA_OPEN_EXISTING);
		  if (fres != FR_OK)
			  break;
		  f_close(&fil);
		  Number++;
	  }
	  Number--;
	  GetLog_filename(filename, Number); // We get filename of last file
	  print("OK: I find last file\n");

	  f_open(&fil, filename, FA_READ);
	  LineNow = SD_CountLines(fil);
	  f_close(&fil);

	  if (LineNow >= MAX_LOG_LINES){
		  LineNow = 0;

		  Number++;
		  GetLog_filename(filename, Number);

		  // Create New File
		  fres = f_open(&fil, filename, FA_WRITE | FA_OPEN_ALWAYS);
		  if(fres != FR_OK) {
			  snprintf(trans_str, 128, "ERROR: Create File (%i)\n", fres);
			  print(trans_str);
			  while(1);
		  }
		  SD_WriteLine(fil, LOG_FILE_HEADER);
		  f_close(&fil);
	  }
	  f_open(&fil, filename, FA_OPEN_APPEND | FA_WRITE);
  }
  else
  {
	  print("OK: Not Founded 'log0.csv'\n");
	  GetLog_filename(filename, Number);

	  // Create New File
	  fres = f_open(&fil, filename, FA_WRITE | FA_OPEN_ALWAYS);
	  if(fres != FR_OK) {
	  	  snprintf(trans_str, 128, "ERROR: Create File (%i)\n", fres);
	  	  print(trans_str);
	  	  while(1);
	  }
	  SD_WriteLine(fil, LOG_FILE_HEADER);
	  f_close(&fil);
	  f_open(&fil, filename, FA_OPEN_APPEND | FA_WRITE);
  }
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  print("\nOK: Now begin...\n");
  HAL_Delay(1000);
  print("____________________\n");

  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
	  if (CANSPI_isBussOff())
	  {
		  print("ERROR: IS BUSS OFF\n");
		  HAL_Delay(1000);
	  }
	  if (CANSPI_isRxErrorPassive()) {
	      print("ERROR: Rx Error Passive\n");
	      HAL_Delay(1000);
	  }
	  if (CANSPI_isTxErrorPassive()) {
	      print("ERROR: Tx Error Passive\n");
	      HAL_Delay(1000);
	  }

	  GetDateTime(dateTime);

	  if(CANSPI_Receive(&rxMessage))
	  {
		  TransformToASCII(ascii_str, rxMessage.array);
		  snprintf(trans_str, 128, "%s;%04lX;%02X %02X %02X %02X %02X %02X %02X %02X;%s\n",
				  dateTime,
				  rxMessage.frame.id,
				  rxMessage.frame.data0,
				  rxMessage.frame.data1,
				  rxMessage.frame.data2,
				  rxMessage.frame.data3,
				  rxMessage.frame.data4,
				  rxMessage.frame.data5,
				  rxMessage.frame.data6,
				  rxMessage.frame.data7,
				  ascii_str);
		  if (!SD_WriteLine(fil, trans_str))
		  {
		  LineNow++;
		  snprintf(trans_str, 64, "%s %d\n", dateTime, LineNow);
		  print(trans_str);
		  HAL_GPIO_TogglePin(LED1_GPIO_Port, LED1_Pin);

		  if (LineNow >= MAX_LOG_LINES) {
		  		  f_close(&fil);
		  		  LineNow = 0;

		  		  Number++;
		  		  GetLog_filename(filename, Number);

		  		  // Create New File
		  		  fres = f_open(&fil, filename, FA_WRITE | FA_OPEN_ALWAYS);
		  		  if(fres != FR_OK) {
		  			  snprintf(trans_str, 128, "ERROR: Create File (%i)\n", fres);
		  			  print(trans_str);
		  			  while(1);
		  		  }
		  		  SD_WriteLine(fil, LOG_FILE_HEADER);
		  	  }
		  }
	  }
  }
  HAL_UART_Transmit(&huart4, (uint8_t *)"What?!", 10, 100);
  f_mount(NULL, "", 0);

  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_LSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.LSIState = RCC_LSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLM = 8;
  RCC_OscInitStruct.PLL.PLLN = 72;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 4;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief RTC Initialization Function
  * @param None
  * @retval None
  */
static void MX_RTC_Init(void)
{

  /* USER CODE BEGIN RTC_Init 0 */
	RTC_TimeTypeDef sTime;
  /* USER CODE END RTC_Init 0 */

  /* USER CODE BEGIN RTC_Init 1 */
	sTime.Hours = -17; // 0 hour, I don`t know why.
	sTime.Minutes = 0;
	sTime.Seconds = 0;
  /* USER CODE END RTC_Init 1 */

  /** Initialize RTC Only
  */
  hrtc.Instance = RTC;
  hrtc.Init.HourFormat = RTC_HOURFORMAT_24;
  hrtc.Init.AsynchPrediv = 127;
  hrtc.Init.SynchPrediv = 255;
  hrtc.Init.OutPut = RTC_OUTPUT_DISABLE;
  hrtc.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
  hrtc.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
  if (HAL_RTC_Init(&hrtc) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN RTC_Init 2 */
  HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BIN); // Установка времени

  /* USER CODE END RTC_Init 2 */

}

/**
  * @brief SPI2 Initialization Function
  * @param None
  * @retval None
  */
static void MX_SPI2_Init(void)
{

  /* USER CODE BEGIN SPI2_Init 0 */

  /* USER CODE END SPI2_Init 0 */

  /* USER CODE BEGIN SPI2_Init 1 */

  /* USER CODE END SPI2_Init 1 */
  /* SPI2 parameter configuration*/
  hspi2.Instance = SPI2;
  hspi2.Init.Mode = SPI_MODE_MASTER;
  hspi2.Init.Direction = SPI_DIRECTION_2LINES;
  hspi2.Init.DataSize = SPI_DATASIZE_8BIT;
  hspi2.Init.CLKPolarity = SPI_POLARITY_LOW;
  hspi2.Init.CLKPhase = SPI_PHASE_1EDGE;
  hspi2.Init.NSS = SPI_NSS_SOFT;
  hspi2.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_4;
  hspi2.Init.FirstBit = SPI_FIRSTBIT_MSB;
  hspi2.Init.TIMode = SPI_TIMODE_DISABLE;
  hspi2.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
  hspi2.Init.CRCPolynomial = 10;
  if (HAL_SPI_Init(&hspi2) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN SPI2_Init 2 */

  /* USER CODE END SPI2_Init 2 */

}

/**
  * @brief UART4 Initialization Function
  * @param None
  * @retval None
  */
static void MX_UART4_Init(void)
{

  /* USER CODE BEGIN UART4_Init 0 */

  /* USER CODE END UART4_Init 0 */

  /* USER CODE BEGIN UART4_Init 1 */

  /* USER CODE END UART4_Init 1 */
  huart4.Instance = UART4;
  huart4.Init.BaudRate = 115200;
  huart4.Init.WordLength = UART_WORDLENGTH_8B;
  huart4.Init.StopBits = UART_STOPBITS_1;
  huart4.Init.Parity = UART_PARITY_NONE;
  huart4.Init.Mode = UART_MODE_TX_RX;
  huart4.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart4.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart4) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN UART4_Init 2 */

  /* USER CODE END UART4_Init 2 */

}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};
/* USER CODE BEGIN MX_GPIO_Init_1 */
/* USER CODE END MX_GPIO_Init_1 */

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOH_CLK_ENABLE();
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOC, SD_CS_Pin|CAN_CS_Pin, GPIO_PIN_SET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(LED1_GPIO_Port, LED1_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pins : SD_CS_Pin CAN_CS_Pin */
  GPIO_InitStruct.Pin = SD_CS_Pin|CAN_CS_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_MEDIUM;
  HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);

  /*Configure GPIO pin : LED1_Pin */
  GPIO_InitStruct.Pin = LED1_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(LED1_GPIO_Port, &GPIO_InitStruct);

/* USER CODE BEGIN MX_GPIO_Init_2 */
/* USER CODE END MX_GPIO_Init_2 */
}

/* USER CODE BEGIN 4 */

/**
 * @brief This function return Date and Time
 * @retval None
 * */
void GetDateTime(char* buffer)
{
    RTC_TimeTypeDef sTime;

    // Получаем текущую дату и время
    HAL_RTC_GetTime(&hrtc, &sTime, RTC_FORMAT_BIN);

    // Форматируем строку времени
    snprintf(buffer, 50, "[%02d:%02d:%02d]",
             sTime.Hours,
             sTime.Minutes,
             sTime.Seconds);
}

void TransformToASCII(char* buffer, uint8_t* data)
{
	for (int i = 6; i < 14; i++)
	{
		uint8_t data_byte = ((uint8_t *)data)[i];
	    if (data_byte >= 32 && data_byte <= 126) {
	        buffer[i-6] = (char)data_byte;
	    } else {
	        buffer[i-6] = '.';
	    }
	}
	buffer[8] = '\0';
}

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */