blob: 1c7f7f3d76a1ae01fe2415c3977886777769ad40 [file] [log] [blame]
Eric Andersenaad1a882001-03-16 22:47:14 +00001/* vi: set sw=4 ts=4: */
2/*
3 * Utility routines.
4 *
Eric Andersenc7bda1c2004-03-15 08:29:22 +00005 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersenaad1a882001-03-16 22:47:14 +00006 *
Denys Vlasenko0ef64bd2010-08-16 20:14:46 +02007 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
Eric Andersenaad1a882001-03-16 22:47:14 +00008 */
Eric Andersenaad1a882001-03-16 22:47:14 +00009#include "libbb.h"
10
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +000011FILE* FAST_FUNC fopen_or_warn(const char *path, const char *mode)
Eric Andersenaad1a882001-03-16 22:47:14 +000012{
Denis Vlasenkoddec5af2006-10-26 23:25:17 +000013 FILE *fp = fopen(path, mode);
14 if (!fp) {
Denis Vlasenko0c97c9d2007-10-01 11:58:38 +000015 bb_simple_perror_msg(path);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000016 //errno = 0; /* why? */
Eric Andersenaad1a882001-03-16 22:47:14 +000017 }
18 return fp;
19}
Denis Vlasenko5415c852008-07-21 23:05:26 +000020
21FILE* FAST_FUNC fopen_for_read(const char *path)
22{
23 return fopen(path, "r");
24}
25
26FILE* FAST_FUNC xfopen_for_read(const char *path)
27{
28 return xfopen(path, "r");
29}
30
31FILE* FAST_FUNC fopen_for_write(const char *path)
32{
33 return fopen(path, "w");
34}
35
36FILE* FAST_FUNC xfopen_for_write(const char *path)
37{
38 return xfopen(path, "w");
39}
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +010040
41static FILE* xfdopen_helper(unsigned fd_and_rw_bit)
42{
43 FILE* fp = fdopen(fd_and_rw_bit >> 1, fd_and_rw_bit & 1 ? "w" : "r");
44 if (!fp)
Denys Vlasenko899ae532018-04-01 19:59:37 +020045 bb_die_memory_exhausted();
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +010046 return fp;
47}
48FILE* FAST_FUNC xfdopen_for_read(int fd)
49{
50 return xfdopen_helper(fd << 1);
51}
52FILE* FAST_FUNC xfdopen_for_write(int fd)
53{
54 return xfdopen_helper((fd << 1) + 1);
55}