在 C 中不使用 sscanf 从字符串中读取数据

问题描述 投票:0回答:1

我正在从 STM32 嵌入式应用程序的 SD 卡读取数据。该数据写入txt文件中。

char resultFormat[100] = "%s\n%s\n%s\n%lf\n%lf\n%lf\n%i\n%i\n%i\n";


void readResult(int indexNumber)
{
    FRESULT fr;
    FIL MyFile;     /* File object */
    size_t read;
    UINT bytesRead;


    FATFS SDFatFs;  /* File system object for SD disk logical drive */

    fr =  f_mount(&SDFatFs, (TCHAR const*)SDPath, 0); //Mounts the file

    char fileName[20];
    char directory[10]= "RESULTS";
    sprintf (fileName, "%s/%i.TXT",directory, indexNumber);

    fr =  f_open(&MyFile, fileName, FA_READ); //Opens the file
    read = f_read( &MyFile, resultBuffer,  sizeof resultBuffer, &bytesRead );   //Writes the txt from the txt file to a string.

    vTaskDelay(200);
    f_close(&MyFile); //Closes the file

    sscanf(resultBuffer, resultFormat, resultDate, resultTime, presetName, &correctedFlash, &observedFlash, &pressure, &flashedStatus, &resultStartTemp, &status);

    sendResultInfo(); //Processes the variables. Not relevant.

    fr = f_mount(NULL, "", 0); //Unmounts the file.

}


我的主要问题是:

char resultFormat[100] = "%s\n%s\n%s\n%lf\n%lf\n%lf\n%i\n%i\n%i\n";
sscanf(resultBuffer, resultFormat, resultDate, resultTime, presetName, &correctedFlash, &observedFlash, &pressure, &flashedStatus, &resultStartTemp, &status);

我有很多变量需要从字符串中读取,如果我更改任何内容,我还必须更改 resultFormat,这可能会导致错误。

现在,变量的数量是可以管理的,但我想知道如果我有更多的数据要从txt文件中读取,比如我有100个不同类型的变量要读取,那么应该如何读取这些数据。在这种情况下,Sscanf 似乎太容易出现人为错误,无法可靠使用,我想知道是否有其他方法可以从字符串中读取数据。 here提供的上一个问题提供了长 sscanf 读取的解决方案,但我想知道是否还有其他解决方案。


我的第二个问题(不确定是否适合这个堆栈,但我的印象是它会被提出)是在不使用txt文件的情况下存储这些数据,并且不将其存储为字符串。

我拥有的数据并不多是字符串,其中一些是整数和双精度数,但存储为字符串。

虽然我当前的系统可以工作(并且有利于调试,因为我可以轻松地从外部读取存储的数据),但我想知道非字符串数据应如何格式化并存储在 SD 卡中。

如果需要更多信息或详细说明,请告诉我。

c string scanf
1个回答
0
投票
  1. \n
    scanf
    格式中几乎不需要。如果你去掉那些,你会得到一个更容易阅读的字符串。
  2. 永远不要使用不是字符串文字的格式字符串来调用
    scanf
    和朋友。编译器编写者投入了大量的工作来捕获格式错误,但是您通过使实际的格式字符串在调用站点不可见而将其全部丢弃。
  3. 考虑使用字符串文字串联来将变量与其格式对齐。

像这样的电话

sscanf(resultBuffer,
       "%s"        "%s"        "%s"        "%lf"            "%lf"           "%lf"      "%i"            "%i"              "%i",
       resultDate, resultTime, presetName, &correctedFlash, &observedFlash, &pressure, &flashedStatus, &resultStartTemp, &status);

几乎可维护。如果您弄乱了格式字符串,使其不再对应于实际参数,您将收到编译器警告。只需查看即可知道格式的哪一部分对应于哪个变量。它唯一的问题是它太长,你不能将它分成几行而不失去视觉对齐。如果您遇到此问题,请将缓冲区调用分成几个较小的调用,或者完全远离

scanf

© www.soinside.com 2019 - 2024. All rights reserved.