Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

perf tools: Add filename__read_str util function

Adding filename__read_str util function to read
text file and return it in the char array.

The interface is:
int filename__read_str(const char *filename, char **buf, size_t *sizep)

Returns 0/-1 if the read suceeded/fail respectively.

buf - place to store the data pointer
size - place to store data size

v2 change:
- better error handling suggested by Namhyung Kim.

Signed-off-by: Jiri Olsa <jolsa@redhat.com>
Cc: Corey Ashford <cjashfor@linux.vnet.ibm.com>
Cc: David Ahern <dsahern@gmail.com>
Cc: Frederic Weisbecker <fweisbec@gmail.com>
Cc: Ingo Molnar <mingo@elte.hu>
Cc: Namhyung Kim <namhyung@kernel.org>
Cc: Paul Mackerras <paulus@samba.org>
Cc: Peter Zijlstra <a.p.zijlstra@chello.nl>
Cc: Steven Rostedt <rostedt@goodmis.org>
Link: http://lkml.kernel.org/r/1386076182-14484-9-git-send-email-jolsa@redhat.com
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>

authored by

Jiri Olsa and committed by
Arnaldo Carvalho de Melo
cef82c9f 3d7c0144

+50
+49
tools/perf/util/util.c
··· 6 6 #endif 7 7 #include <stdio.h> 8 8 #include <stdlib.h> 9 + #include <string.h> 10 + #include <errno.h> 9 11 #include <linux/kernel.h> 10 12 11 13 /* ··· 431 429 *value = atoi(line); 432 430 err = 0; 433 431 } 432 + 433 + close(fd); 434 + return err; 435 + } 436 + 437 + int filename__read_str(const char *filename, char **buf, size_t *sizep) 438 + { 439 + size_t size = 0, alloc_size = 0; 440 + void *bf = NULL, *nbf; 441 + int fd, n, err = 0; 442 + 443 + fd = open(filename, O_RDONLY); 444 + if (fd < 0) 445 + return -errno; 446 + 447 + do { 448 + if (size == alloc_size) { 449 + alloc_size += BUFSIZ; 450 + nbf = realloc(bf, alloc_size); 451 + if (!nbf) { 452 + err = -ENOMEM; 453 + break; 454 + } 455 + 456 + bf = nbf; 457 + } 458 + 459 + n = read(fd, bf + size, alloc_size - size); 460 + if (n < 0) { 461 + if (size) { 462 + pr_warning("read failed %d: %s\n", 463 + errno, strerror(errno)); 464 + err = 0; 465 + } else 466 + err = -errno; 467 + 468 + break; 469 + } 470 + 471 + size += n; 472 + } while (n > 0); 473 + 474 + if (!err) { 475 + *sizep = size; 476 + *buf = bf; 477 + } else 478 + free(bf); 434 479 435 480 close(fd); 436 481 return err;
+1
tools/perf/util/util.h
··· 308 308 void free_srcline(char *srcline); 309 309 310 310 int filename__read_int(const char *filename, int *value); 311 + int filename__read_str(const char *filename, char **buf, size_t *sizep); 311 312 #endif /* GIT_COMPAT_UTIL_H */