File: secshms.c

package info (click to toggle)
gramofile 1.6-4
  • links: PTS
  • area: main
  • in suites: woody
  • size: 820 kB
  • ctags: 536
  • sloc: ansic: 10,238; makefile: 55
file content (105 lines) | stat: -rw-r--r-- 2,103 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/* Seconds to Hour:Minute:Seconds and back

 * Copyright (C) 1998 J.A. Bezemer
 *
 * Licensed under the terms of the GNU General Public License.
 * ABSOLUTELY NO WARRANTY.
 * See the file `COPYING' in this directory.
 */

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


void
secs2hms (long seconds, char *outstring)	/*  3610  ->  1:00:10  */
{
  sprintf (outstring, "%ld:%02ld:%02ld", seconds / 3600,
	   (seconds / 60) % 60,
	   seconds % 60);
}

void
fsec2hmsf (double seconds, char *outstring)
{
  double intpart = 0;
  double floatpart;
  long i;
  char helpstring[250];

  floatpart = modf (seconds, &intpart);
  i = intpart;
  secs2hms (i, outstring);

  sprintf (helpstring, "%.3f", floatpart);
  strcat (outstring, helpstring + 1);
}

int
hmsf2fsec (char *instring, double *seconds)
/* returns 0: failure, 1: success; instring will be modified. */
{
  char *charptr;
  int i = 0;

  if (!strlen (instring))
    return 0;			/* empty string */

  *seconds = 0;

  /* seconds */

  charptr = strrchr (instring, ':');
  if (charptr == NULL)
    charptr = instring;
  else
    {
      *charptr = '\0';		/* put a '\0' in place of the ':' */
      charptr++;
    }
  /* charptr is now start of seconds */
  if (!sscanf (charptr, "%lf", seconds))
    return 0;

  if (charptr == instring)
    return 1;

  /* minutes */

  charptr = strrchr (instring, ':');
  if (charptr == NULL)
    charptr = instring;
  else
    {
      *charptr = '\0';		/* put a '\0' in place of the ':' */
      charptr++;
    }
  /* charptr is now start of minutes */
  if (!sscanf (charptr, "%d", &i))
    return 0;
  *seconds += i * 60;

  if (charptr == instring)
    return 1;

  /* hours */

  charptr = strrchr (instring, ':');
  if (charptr == NULL)
    charptr = instring;
  else
    {
      *charptr = '\0';		/* put a '\0' in place of the ':' */
      charptr++;
    }
  /* charptr is now start of hours */
  if (!sscanf (charptr, "%d", &i))
    return 0;
  *seconds += i * 3600;

  if (charptr == instring)
    return 1;			/* nothing before hours: OK */

  return 0;			/* something before hours. days?? */
}