尝试从文件中读取特定格式

时间:2020-04-21 09:23:27

标签: c

您好,我正在尝试从文件中读取特定格式,并将所需的值放入2d数组中。

这是格式“ timestamp1”:“ value1”,“ timestamp2”:“ value2”,…,“ timestampN”:“ valueN”

我需要时间戳和值而不是引号。

文件洞察力 could be inserted as text, but the OP didn't make it

每行都等于新一天。

#include <stdio.h>
#include <stdlib.h>

#define DAT_MAX_LINES 1000

int main(void)
    {
        char array[DAT_MAX_LINES][2];
        int n = 0;
        int i;

        FILE * pRead = fopen("tempm.txt", "r");

    if (!pRead)
    {
        printf("File cannot be opened\n");
        return EXIT_FAILURE;
    }

    printf("Contents of tempm.txt:\n");

    while ( (n < DAT_MAX_LINES) && (!feof(pRead)) )
    {
        fscanf(pRead,"\"%s\": \"%s\",%n", &array[n][0], &array[n][1]);
        n++;
    }

    fclose(pRead);

    for (i = 0; i < n; i++)
    {
        printf("%s\" %s\",%n", i, array[i][0], array[i][1]);
    }

    return EXIT_SUCCESS;
}

首先,我将这些值作为字符串,然后将这些值转换为双精度。我不确定是否可以从头开始。

3 个答案:

答案 0 :(得分:0)

%s转换说明符不会在模式中向前看,只是因为您在说明符后面加上了一个相当大的含义,当它找到报价时,它不会使实际转换停止。

您可以使用%[],但是使用fscanf()来构建解析器非常困难。如果它是真正基于行的,请考虑使用fgets()读取整行,然后进行解析。

答案 1 :(得分:0)

首先,您必须声明2个用于存储值和时间戳的数组:

#define MAX_LENGTH 1000 // for example
#define MAX_NUM_VALUES 4000
...
char timestamps[MAX_NUM_VALUES][MAX_LENGTH];
int values[MAX_NUM_VALUES];

尝试使用fgets()逐行阅读:

char line[MAX_LENGTH];
while ( fgets(line, sizeof(line), pRead))
{
    // get value in each line
}

从文本文件中逐行获取后,可以使用strtok以逗号,分隔行,然后使用sscanf获取每一行的时间戳和值。

    while ( fgets(line, sizeof(line), pRead))
    {
        char * token = strtok(line, ",");
        while(token != NULL) {
            printf("%s\n", token);
            sscanf(token," \"%s\": \"%s\"", timestamps[n], &value[n]);
            token = strtok(NULL, ",");
            n++;
        }
    }

答案 2 :(得分:0)

你好,过了一会儿,我设法从文件中读取了特定的格式,并将它们放到一个数组中。现在,我想删除引号,并创建一个带有时间戳和值的二维数组。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main () {
   char c[100000];
   FILE *fptr;
    if ((fptr = fopen("tempm.txt", "r")) == NULL) {
        printf("Error! opening file");
        // Program exits if file pointer returns NULL.
        exit(1);
    }

     //reads text until newline is encountered
    fscanf(fptr, "%[^\n]", c);
    printf("Data from the file:\n%s",c);  //raw data of the file
    fclose(fptr);

   int i=0;
   char *MixedArray[10000];
   char *token = strtok(c, ",");
   while( token != NULL ) {
      MixedArray[i]=token;
      token = strtok(NULL, ",");
      printf("%d %s\n",i,MixedArray[i]);
      i++;
  }
     return 0;
}

我的结果: https://i.imgur.com/2LHdevo.png 没有足够的代表来发布图片