2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C言語 err, errx関数

Last updated at Posted at 2020-09-15

概要

フォーマットされたエラーメッセージを表示して、終了します。

Synopsis

# include <err.h>

void err( int eval, const char *fmt, ...);

void errx( int eval, const char *fmt, ...);

Arguments

eval

The value to use as the exit code of the process.
プロセスの終了コードとして使用する値。

fmt

NULL, or a printf()-style string used to format the message.
NULL、またはメッセージのフォーマットに使用されるprintf()スタイルの文字列。

Additional arguments

As required by the format string.
書式文字列での必要に応じて。

詳細

関数のerr()およびwarn()ファミリーは、stderrにフォーマットされたエラーメッセージを表示します。

名前にxが含まれていない関数は、errnoの現在の値に関連付けられている文字列を表示します。

vが付いているものは「可変引数」関数です。

errを持つものは戻るのではなく終了します。

Function errno string? Varargs? Exits?
err() Yes No Yes
errx() No No Yes
verr() Yes Yes Yes
verrx() No Yes Yes
vwarn() Yes Yes No
vwarnx() No Yes No
warn() Yes No No
warnx() No No No

err()の詳細

err()関数は、以下で構成されるメッセージを生成します。

  • プログラム名の最後のコンポーネント、それに続くコロンとスペース
  • fmt引数がNULLでない場合、フォーマットされたメッセージの後にコロンとスペース
  • errnoの現在の値に関連付けられた文字列
  • 改行

メッセージの出力後、引数evalの値で終了します。

用例

if ((p = malloc(size)) == NULL)
   err(1, NULL);
if ((fd = open(file_name, O_RDONLY, 0)) == -1)
   err(1, "%s", file_name);

出力例

a.out: test: Undefined error: 0

自作コード

コードで書くなら以下です。
※正確に再現できているのか確証は無いです。

char *program_name;

void	ft_err(int eval, const char *fmt)
{
	printf("%s", basename(program_name));
	printf("%s", ": ");
	if (fmt)
	{
		printf("%s", fmt);
		printf("%s", ": ");
	}
	printf("%s", strerror(errno));
	printf("%s", "\n");
	exit(eval);
}

errx()の詳細

errx()関数は、errnoに関連付けられた文字列を含まないことを除いて、同様のメッセージを生成します。

メッセージは以下で構成されます。

  • プログラム名の最後のコンポーネント、それに続くコロンとスペース
  • fmt引数がNULLでない場合、フォーマットされたメッセージの後にコロンとスペース
  • 改行

err()およびerrx()関数は戻りませんが、引数evalの値で終了します

用例

if (tm.tm_hour < START_TIME)
    errx(1, "too early, wait until %s", start_time_string);

参考

QNX SDP 6.5.0 err(), errx()

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?