utils.c
Go to the documentation of this file.
1 #include <string.h>
2 #include <errno.h>
3 
4 #include "csm_all.h"
5 
7 FILE * open_file(const char *filename, const char*mode);
8 
9 
10 FILE * open_file(const char *filename, const char*mode) {
11  FILE*file = fopen(filename, mode);
12  if(file==NULL) {
13  sm_error("Could not open file '%s': %s.\n", filename, strerror(errno));
14  return 0;
15  }
16  return file;
17 }
18 
19 FILE * open_file_for_reading(const char*filename) {
20  if(!strcmp(filename, "-" )) return stdin;
21  if(!strcmp(filename, "stdin")) return stdin;
22  return open_file(filename, "r");
23 }
24 
25 FILE * open_file_for_writing(const char*filename) {
26  if(!strcmp(filename, "-" )) return stdout;
27  if(!strcmp(filename, "stdout")) return stdout;
28  if(!strcmp(filename, "stderr")) return stderr;
29  return open_file(filename, "w");
30 }
31 
32 void my_basename(const char *file, char*dest) {
33  const char *start = strrchr(file, DIR_SEPARATOR);
34  if(!start)
35  strcpy(dest, file);
36  else
37  strcpy(dest, start+1);
38 }
39 
40 void my_basename_no_suffix(const char *file, char*dest) {
41  const char *start = strrchr(file, DIR_SEPARATOR);
42  if(!start) start = file; else start += 1;
43  const char *end = strrchr(file, '.');
44  if(!end || end<start) end = start + strlen(start);
45 
46  strncpy(dest, start, (size_t) (end-start));
47  dest[end-start] = '\0';
48 
49 /* printf("start: '%s' end: '%s' base_no_suffix: '%s'\n", start, end, dest);*/
50 }
51 
52 void my_no_suffix(const char *file, char*dest) {
53  const char *end = strrchr(file, '.');
54  if(!end) end = file + strlen(file);
55  strncpy(dest, file, (size_t) (end-file) );
56  dest[end-file] = '\0';
57 }
58 
59 
61 char * my_strdup(const char *s) {
62  size_t len = strlen(s) + 1; /* null byte */
63  char * t = (char*) malloc(len);
64  memcpy(t,s,len);
65  return t;
66 }
67 
#define DIR_SEPARATOR
Definition: utils.h:18
void my_basename_no_suffix(const char *file, char *dest)
Definition: utils.c:40
FILE * open_file_for_writing(const char *filename)
Definition: utils.c:25
void my_basename(const char *file, char *dest)
Definition: utils.c:32
FILE * open_file(const char *filename, const char *mode)
Definition: utils.c:10
void my_no_suffix(const char *file, char *dest)
Definition: utils.c:52
FILE * open_file_for_reading(const char *filename)
Definition: utils.c:19
char * my_strdup(const char *s)
Definition: utils.c:61
void sm_error(const char *msg,...)
Definition: logging.c:49


csm
Author(s): Andrea Censi
autogenerated on Tue May 11 2021 02:18:23