File: helper.c

package info (click to toggle)
orange 0.2-3
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 1,044 kB
  • ctags: 299
  • sloc: sh: 7,824; ansic: 2,419; makefile: 83
file content (98 lines) | stat: -rw-r--r-- 2,081 bytes parent folder | download
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
/* $Id: helper.c,v 1.3 2003/09/12 18:44:01 twogood Exp $ */
#define _BSD_SOURCE 1
#include "liborange_internal.h"
#include <synce_log.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

bool orange_make_sure_directory_exists(const char* directory)/*{{{*/
{
  struct stat dir_stat;
  const char* p = directory;

  while (p && *p)
  {
    if ('/' == *p)
      p++;
    else if (0 == strncmp(p, "./", 2))
      p+=2;
    else if (0 == strncmp(p, "../", 3))
      p+=3;
    else
    {
      char* current = strdup(directory);
      const char* slash = strchr(p, '/');

      if (slash)
        current[slash-directory] = '\0';

      if (stat(current, &dir_stat) < 0)
      {
        if (mkdir(current, 0700) < 0)
        {
          fprintf(stderr, "Failed to create directory %s\n", directory);
          return false;
        }
      }

      p = slash;
    }
  }

  return true;
}/*}}}*/

long orange_fsize(FILE* file)
{
  long result;
  long previous = ftell(file);
  fseek(file, 0L, SEEK_END);
  result = ftell(file);
  fseek(file, previous, SEEK_SET);
  return result;
}

bool orange_write(const uint8_t* output_buffer, size_t output_size, const char* output_directory, const char* basename)/*{{{*/
{
  bool success = false;
  char filename[256];
  FILE* output = NULL;
  char*p;

  /* allow basename to contain path components... */
  
  snprintf(filename, sizeof(filename), "%s/%s", output_directory, basename);
  p = strrchr(filename, '/');
  assert(p);
  *p = '\0';

  if (!orange_make_sure_directory_exists(filename))
    goto exit;

  snprintf(filename, sizeof(filename), "%s/%s", output_directory, basename);

  output = fopen(filename, "w");
  if (!output)
  {
    synce_error("Failed to open file for writing: '%s'", filename);
    goto exit;
  }

  if (output_size != fwrite(output_buffer, 1, output_size, output))
  {
    synce_error("Failed to write %i bytes to file '%s'", output_size, filename);
    goto exit;
  }

  success = true;

exit:
  FCLOSE(output);
  return success;
}/*}}}*/