File: file.c

package info (click to toggle)
poc-streamer 0.4.2-8
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,000 kB
  • sloc: ansic: 8,782; makefile: 307; ruby: 152; perl: 135; yacc: 115; lex: 36; sh: 30
file content (130 lines) | stat: -rw-r--r-- 2,253 bytes parent folder | download | duplicates (5)
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
/*C
  (c) 2005 bl0rg.net
**/

#include "conf.h"

#include <assert.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>

#include "file.h"
#include "misc.h"

/*M
  \emph{Read and retry on interrupted system calls.}
**/ 
int file_read(file_t *file, unsigned char *buf, size_t size) {
  assert(file != NULL);
  assert(buf != NULL);
  assert(size > 0);

  return unix_read(file->fd, buf, size);
}

/*M
  \emph{Seek forward in the file.}
**/
int file_seek_fwd(file_t *file, size_t size) {
  if (lseek(file->fd, size, SEEK_CUR) < 0)
    return 0;
  else
    return 1;
}

/*M
  \emph{Open a file.}

  Return 0 on error, 1 on success. To read from STDIN, call with "-"
  as filename.
**/
int file_open_read(file_t *file, char *filename) {
  assert(file != NULL);
  assert(filename != NULL);

  if (strcmp(filename, "-") == 0) {
    /* read from stdin */
    file->fd   = STDIN_FILENO;
    file->size = 0;
  } else {
    file->fd = open(filename, O_RDONLY);

    if (file->fd < 0) {
      perror("open");
      return 0;
    }

    struct stat sb;
    if (stat(filename, &sb) < 0) {
      perror("stat");
      return 0;
    }
    file->size = (unsigned long)sb.st_size;
  }

  file->offset = 0;

  return 1;
}

/*M
  \emph{Write a buffer to filedescriptor fd.}
**/
int file_write(file_t *file, unsigned char *buf, size_t size) {
  assert(file != NULL);
  assert(buf != NULL);

  return unix_write(file->fd, buf, size);
}

/*M
  \emph{Open a file for writing.}
**/
int file_open_write(file_t *file, char *filename) {
  assert(file != NULL);
  assert(filename != NULL);

  if (!strcmp(filename, "-"))
    /* write to stdout */
    file->fd = STDOUT_FILENO;
  else {
    file->fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC,
                    S_IRWXU | S_IRGRP | S_IROTH);

    if (file->fd < 0) {
      perror("open");
      return 0;
    }
  }

  file->offset = 0;

  return 1;
}

/*M
  \emph{Close a file.}

  Return 0 on error and 1 on success.
**/
int file_close(file_t *file) {
  assert(file != NULL);

  if (file->fd != STDIN_FILENO) {
    if (close(file->fd) < 0) {
      perror("close");
      return 0;
    }
  }

  return 1;
}

/*C
**/