同じファイルかどうか判定する

test file1 -ef file2 はポータビリティが怪しいということで、同じ機能を Perl で書いてみる。

#!/usr/bin/perl

use strict;
use warnings;
use File::stat;

sub usage {
    print STDERR "Usage: $0 file1 file2\n";
}

sub main {
    if (@ARGV != 2) {
        usage;
        exit 1;
    }

    my ($file1, $file2) = @ARGV;

    my $st1 = stat $file1;
    my $st2 = stat $file2;

    if (not defined $st1) {
        exit 1;
    }

    if (not defined $st2) {
        exit 1;
    }

    if ($st1->dev == $st2->dev and $st1->ino == $st2->ino) {
        exit 0;
    }
    else {
        exit 1;
    }
}

main;

GNU coreutils の readlink(1) が使えたとして、代替になるかといえば hard link の場合に判定失敗するので、微妙なところ。

typedef クイズ

C の型宣言って初心者には難しいよね、というネタ。

ポインタ編

以下の2つの文が同じ意味になるように typedef 文を書け。

int *p;
pint p;

配列編

以下の2つの文が同じ意味になるように、typedef 文を書け。

int a[10];
aint a;

関数ポインタ編

以下のプログラムで10が出力されるように typedef を追加せよ。

#include <stdio.h>

static
int func()
{
  return 10;
}

int
main()
{
  pfunc f = func;
  printf("%d\n", f());
  return 0;
}

関数ポインタの配列編

以下のプログラムがコンパイルできるように、pfunc_array を typedef で宣言せよ。

#include <stdio.h>
#include <math.h>

int
main()
{
  int i;
  pfunc_array funcs = {sin, cos, tan};
  for (i = 0; i < 3; i++)
    {
      printf("%f\n", funcs[i](0.0));
    }
  return 0;
}