blob: 4d4b780258dd9617811f3cf41ae85deb4977e36f [file] [log] [blame]
Daniel Lezcano88b38e32011-06-15 15:45:12 +02001/*******************************************************************************
2 * Copyright (C) 2011, Linaro Limited.
3 *
4 * This file is part of PowerDebug.
5 *
6 * All rights reserved. This program and the accompanying materials
7 * are made available under the terms of the Eclipse Public License v1.0
8 * which accompanies this distribution, and is available at
9 * http://www.eclipse.org/legal/epl-v10.html
10 *
11 * Contributors:
12 * Daniel Lezcano <daniel.lezcano@linaro.org> (IBM Corporation)
13 * - initial API and implementation
14 *******************************************************************************/
15
16#define _GNU_SOURCE
17#include <stdio.h>
18#undef _GNU_SOURCE
19#include <stdlib.h>
20
21/*
22 * This functions is a helper to read a specific file content and store
23 * the content inside a variable pointer passed as parameter, the format
24 * parameter gives the variable type to be read from the file.
25 *
26 * @path : directory path containing the file
27 * @name : name of the file to be read
28 * @format : the format of the format
29 * @value : a pointer to a variable to store the content of the file
30 * Returns 0 on success, -1 otherwise
31 */
32int file_read_value(const char *path, const char *name,
33 const char *format, void *value)
34{
35 FILE *file;
36 char *rpath;
37 int ret;
38
39 ret = asprintf(&rpath, "%s/%s", path, name);
40 if (ret < 0)
41 return ret;
42
43 file = fopen(rpath, "r");
44 if (!file) {
45 ret = -1;
46 goto out_free;
47 }
48
49 ret = fscanf(file, format, value) == EOF ? -1 : 0;
50
51 fclose(file);
52out_free:
53 free(rpath);
54 return ret;
55}
Shaojie Sun8ac4a2e2013-07-29 20:11:46 +080056
57/*
58 * This functions is a helper to write a specific file content and store
59 * the content inside a variable pointer passed as parameter, the format
60 * parameter gives the variable type to be write to the file.
61 *
62 * @path : directory path containing the file
63 * @name : name of the file to be read
64 * @format : the format of the format
65 * @value : a pointer to a variable to store the content of the file
66 * Returns 0 on success, -1 otherwise
67 */
68int file_write_value(const char *path, const char *name,
69 const char *format, void *value)
70{
71 FILE *file;
72 char *rpath;
73 int ret;
74
75 ret = asprintf(&rpath, "%s/%s", path, name);
76 if (ret < 0)
77 return ret;
78
79 file = fopen(rpath, "w");
80 if (!file) {
81 ret = -1;
82 goto out_free;
83 }
84
85 ret = fprintf(file, format, value) < 0 ? -1 : 0;
86
87 fclose(file);
88out_free:
89 free(rpath);
90 return ret;
91}