source: MondoRescue/branches/3.2/mondo/src/lib/mr_file.c@ 3612

Last change on this file since 3612 was 3612, checked in by Bruno Cornec, 7 years ago

Addition of a new mr_getcwd function

  • Property svn:eol-style set to native
File size: 2.4 KB
Line 
1/* mr_file.c
2 *
3 * $Id$
4 *
5 * File management for mondo
6 * Code (c)2006 Bruno Cornec <bruno@mondorescue.org>
7 *
8 * Provided under the GPLv2
9 */
10
11
12#include <stdio.h>
13#include <sys/types.h>
14#include <sys/stat.h>
15#include <stdlib.h>
16#include <errno.h>
17#include <unistd.h>
18
19#include "mr_err.h"
20#include "mr_msg.h"
21
22/*open and read file: each call must be coupled with mr_conf_close
23 function: return 0 if success*/
24FILE *mr_fopen_int(const char *path, const char *mode,int line, char *file) {
25 FILE *fd = NULL;
26
27 if ((fd = fopen(path, mode)) == NULL) {
28 mr_msg_int(1,line,file,"mr_fopen_int","Unable to open %s",path);
29 mr_exit(-1,"Exiting");
30 }
31 return(fd);
32}
33
34void mr_fprintf_int(FILE *fd, int line, char *file, const char *fmt, ...) {
35
36 va_list args;
37
38 if (fd == NULL) {
39 mr_msg_int(1,line,file,"mr_fprintf_int","fd is NULL.\nShould NOT happen.");
40 mr_exit(-1,"Exiting");
41 }
42 va_start(args,fmt);
43 if (vfprintf(fd, fmt, args) < 0) {
44 mr_msg_int(1,line,file,"mr_fprintf_int","Unable to print to fd");
45 mr_exit(-1,"Exiting");
46 }
47 va_end(args);
48}
49
50void mr_fclose_int(FILE **fd, int line, char *file) {
51
52 if (fd == NULL) {
53 mr_msg_int(1,line,file,"mr_fclose_int","fd is NULL.\nShould NOT happen.");
54 mr_exit(-1,"Exiting");
55 }
56 if (*fd == NULL) {
57 mr_msg_int(1,line,file,"mr_fclose_int","File descriptor is NULL.\nShould NOT happen.");
58 mr_exit(-1,"Exiting");
59 }
60 if (fclose(*fd) < 0) {
61 mr_msg_int(1,line,file,"mr_fclose_int","Unable to close File Descriptor");
62 }
63 *fd = NULL;
64}
65
66void mr_mkdir_int(const char *pathname, mode_t mode, int line, char *file) {
67
68 if (mkdir(pathname,mode) != 0) {
69 mr_msg_int(1,line,file,"mr_mkdir_int","Unable to create directory %s",pathname);
70 mr_exit(-1,"Exiting");
71 }
72}
73
74/* Version of getcwd using dynamically allocated memory. Cf: man 3p getcwd */
75char *mr_getcwd_int(int line, char *file) {
76
77long path_max;
78size_t size;
79char *buf;
80char *ptr;
81
82path_max = pathconf(".", _PC_PATH_MAX);
83if (path_max == -1) {
84 size = (size_t)512;
85} else if (path_max > 10240) {
86 size = (size_t)10240;
87} else {
88 size = (size_t)path_max;
89}
90
91for (buf = ptr = NULL; ptr == NULL; size *= 2) {
92 if ((buf = realloc(buf, size)) == NULL) {
93 mr_msg_int(1,line,file,"mr_getcwd","Unable to realloc memory");
94 mr_exit(-1,"Exiting");
95 }
96
97 ptr = getcwd(buf, size);
98 if (ptr == NULL && errno != ERANGE) {
99 mr_msg_int(1,line,file,"mr_getcwd","Unable to get current working directory");
100 mr_exit(-1,"Exiting");
101 }
102return(buf);
103}
104}
Note: See TracBrowser for help on using the repository browser.