Checked file stat before realpath
[platform/core/connectivity/stc-manager.git] / src / helper / helper-file.c
1 /*
2  * Copyright (c) 2016 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "helper-file.h"
18
19 #define BUF_MAX         (BUFSIZ)
20 #define BUF_INC_SIZE    (512 << 10)
21
22 int fwrite_str(const char *path, const char *str)
23 {
24         _cleanup_fclose_ FILE *f = NULL;
25         int ret;
26         char * t;
27         struct stat stat_buf;
28
29         assert(path);
30         assert(str);
31
32         if (stat(path, &stat_buf) == 0) {
33                 t = realpath(path, NULL);
34                 ret_value_errno_msg_if(!t, -errno,
35                                        "Fail to get realpath %s", path);
36                 free(t);
37         }
38
39         f = fopen(path, "w");
40         ret_value_errno_msg_if(!f, -errno,
41                                "Fail to open file %s", path);
42
43         ret = fputs(str, f);
44         ret_value_errno_msg_if(ret == EOF, errno ? -errno : -EIO,
45                                "Fail to write file");
46
47         return STC_ERROR_NONE;
48 }
49
50 int fwrite_uint(const char *path, const uint32_t number)
51 {
52         _cleanup_free_ char *digit_buf = NULL;
53         int ret;
54
55         ret = asprintf(&digit_buf, "%d", number);
56         ret_value_errno_msg_if(ret < 0, -ENOMEM,
57                                "sprintf failed\n");
58
59         return fwrite_str(path, digit_buf);
60 }
61
62 int fread_uint(const char *path, uint32_t *number)
63 {
64         _cleanup_fclose_ FILE *f = NULL;
65         int ret;
66
67         f = fopen(path, "r");
68         ret_value_errno_msg_if(!f, -errno,
69                                "Fail to open %s file.", path);
70
71         ret = fscanf(f, "%u", number);
72         ret_value_errno_msg_if(ret == EOF, -errno,
73                                "Fail to read file\n");
74
75         return STC_ERROR_NONE;
76 }