如何将文件中的时间转换为C中的结构?

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

我必须制作一个函数,使用其他函数将文件中的数据(时间)转换为结构。

文件中的数据看起来像这样:

  • id; sensor_id; time; m3
  • 12899; 1; 2018-06-01 01:00:00; 0.0000

这就是结构的外观。

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

typedef struct { 
int year; 
int month; 
int day; 
int hour; 
int min; 
int sec; 
int dayInWeek; 
}tDateTime;

以及函数的声明。我已经解决了“ giveDayInWeek”功能。

tDateTime dejDateTime(char* datetime) //converts input from text file (2018-05-01 01:00:00) into structure, with using giveDayInWeek

int giveDayInWeek(int y, int m, int d) //returns dan in a week (0-Monday,…,6-Sunday) 
{
    static int t[] = { 0,3,2,5,0,3,5,1,4,6,2,4 };
    y -= m < 3;
    return (y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7;
}

我真的很乐意提供帮助。谢谢

c datetime data-structures structure
1个回答
0
投票

[一种好的方法是,有一个函数返回您感兴趣的每个值(getYeargetMonth,...),该函数接收该行作为输入,并返回所需的值:

#include <stdio.h>
#include <string.h>
#define YEAR_LEN 4

typedef struct { 
  int year; 
  int month; 
  int day; 
  int hour; 
  int min; 
  int sec; 
  int dayInWeek; 
}tDateTime;

int getYear(char* p_line){
  char year[YEAR_LEN+1];
  strncpy(year, p_line+8, 4);
  year[YEAR_LEN] = '\0';   /* null character manually added */
  return atoi(year);
}

int main(int argc, char** argv){
  char const* const fileName = argv[1];
  FILE* file = fopen("data.txt", "r");
  char line[256];
  tDateTime dt;

  while (fgets(line, sizeof(line), file)) {
    printf("line: %s\n", line);
    dt.year = getYear(line);
    printf("%d\n", dt.year);
  }

  fclose(file);
  return 0;
}

在工作之后,您还可以将所有函数调用分组到另一个函数中(类似于getData),这样,代码将更加井井有条,更易于维护。

类似:

tDateTime getData(char* p_line){
  tDateTime res;
  res.year = getYear(p_line); 
  res.month = getMonth(p_line);
  return res;
}
© www.soinside.com 2019 - 2024. All rights reserved.