디시인사이드 갤러리

갤러리 이슈박스, 최근방문 갤러리

갤러리 본문 영역

Ada 코드 다시..

나르시갤로그로 이동합니다. 2025.07.22 23:58:25
조회 53 추천 1 댓글 0

Ada 코드입니다.


Cada는 C - Ada 바딩인 라이브러리입니다.


재업 완료

ㅋㅋㅋ


여신






with System;

with Interfaces.C;

with Cada.Types;

with Cada.Error;

with sys_stat_h;

with sys_types_h;

with System.Storage_Elements;

with errno_h;

with unistd_h;


package body Cada.File is

  use type Interfaces.C.Int;

  use type Interfaces.C.long;


  function c_open2 (path  : Interfaces.C.Char_Array;

                    flags : Interfaces.C.Int) return File_Descriptor;

  function c_open3 (path  : Interfaces.C.Char_Array;

                    flags : Interfaces.C.Int;

                    mode  : sys_types_h.mode_t) return File_Descriptor;

  pragma import (c, c_open2, "open");

  pragma import (c, c_open3, "open");


  function open (path  : String;

                 flags : File_Flags) return Object is

    new_fd : constant File_Descriptor :=

      c_open2 (Interfaces.C.to_c (path), Interfaces.C.Int (flags));

  begin

    if new_fd = -1 then

      declare

        error_code : constant Interfaces.C.int := Cada.Error.get_errno;

        error_msg  : constant String           :=

          "open(2) failed for path """ & path & """ (errno: " & error_code'image & ")";

      begin

        case error_code is

          when errno_h.EACCES =>

            raise Cada.Error.Permission_Denied with error_msg;

          when errno_h.ENOENT =>

            raise Cada.Error.No_Such_File_Or_Directory with error_msg;

          when errno_h.EEXIST =>

            raise Cada.Error.File_Exists with error_msg;

          when errno_h.EISDIR =>

            raise Cada.Error.Is_A_Directory with error_msg;

          when errno_h.ENOTDIR =>

            raise Cada.Error.Not_A_Directory with error_msg;

          when others =>

            declare

              errno_text : constant String := Cada.Error.get_error_message(error_code);

            begin

              raise Cada.Error.Unknown_Error with errno_text & ": " & error_msg;

            end;

        end case;

      end;

    end if;

    return (Ada.Finalization.Controlled with fd => new_fd);

  end open;


  -- open implementation (3 arguments)

  function open (path  : String;

                 flags : File_Flags;

                 mode  : Cada.Types.File_Mode) return Object is

    new_fd : constant File_Descriptor := c_open3 (Interfaces.C.to_c (path),

                                                  Interfaces.C.Int (flags),

                                                  sys_types_h.mode_t (mode));

  begin

    if new_fd = -1 then

      declare

        error_code : constant Interfaces.C.int := Cada.Error.get_errno;

        error_msg  : constant String           :=

          "open(2) failed for path """ & path & """ (errno: " & error_code'image & ")";

      begin

        case error_code is

          when errno_h.EACCES =>

            raise Cada.Error.Permission_Denied with error_msg;

          when errno_h.ENOENT =>

            raise Cada.Error.No_Such_File_Or_Directory with error_msg;

          when errno_h.EEXIST =>

            raise Cada.Error.File_Exists with error_msg;

          when errno_h.EISDIR =>

            raise Cada.Error.Is_A_Directory with error_msg;

          when errno_h.ENOTDIR =>

            raise Cada.Error.Not_A_Directory with error_msg;

          when others =>

            declare

              errno_text : constant String := Cada.Error.get_error_message(error_code);

            begin

              raise Cada.Error.Unknown_Error with errno_text & ": " & error_msg;

            end;

        end case;

      end;

    end if;

    return (Ada.Finalization.Controlled with fd => new_fd);

  end open;


  procedure close (self : in out Object) is

    result : constant Interfaces.C.int := unistd_h.close (Interfaces.C.Int (self.fd));

  begin

    if result = -1 then

      -- Embed the error handling logic directly.

      declare

        error_code : constant Interfaces.C.int := Cada.Error.get_errno;

        error_msg  : constant String           :=

          "close(2) failed for fd " & self.fd'image &

          " (errno: " & error_code'image & ")";

      begin

        case error_code is

          when errno_h.EBADF => -- Bad file descriptor

            raise Cada.Error.Bad_File_Descriptor with error_msg;

          when errno_h.EINTR => -- Interrupted system call

            raise Cada.Error.Interrupted_System_Call with error_msg;

          when errno_h.EIO =>   -- I/O error

            raise Cada.Error.Input_Output_Error with error_msg;

          when others =>

            declare

              errno_text : constant String := Cada.Error.get_error_message(error_code);

            begin

              raise Cada.Error.Unknown_Error with errno_text & ": " & error_msg;

            end;

        end case;

      end;

    end if;

    self.fd := -1;

  end close;


  function write (self   : in Object;

                  buffer : in System.Storage_Elements.Storage_Array)

    return Natural is

    bytes_written : constant sys_types_h.ssize_t :=

      unistd_h.write (Interfaces.C.Int (self.fd),

                      buffer'address, buffer'length);

  begin

    if bytes_written = -1 then

      -- [!] 오류 처리 로직을 내부에 직접 작성

      declare

        error_code : constant Interfaces.C.int := Cada.Error.get_errno;

        error_msg  : constant String           :=

          "write(2) failed for fd " & self.fd'image &

          " (errno: " & error_code'image & ")";

      begin

        case error_code is

          when errno_h.EBADF => -- Bad file descriptor

            raise Cada.Error.Bad_File_Descriptor with error_msg;

          when errno_h.EPIPE => -- Broken pipe

            raise Cada.Error.Broken_Pipe with error_msg;

          when errno_h.EINTR => -- Interrupted system call

            raise Cada.Error.Interrupted_System_Call with error_msg;

          when errno_h.EAGAIN => -- (or EWOULDBLOCK) Resource temporarily unavailable

            raise Cada.Error.Resource_Temporarily_Unavailable with error_msg;

          when errno_h.EFBIG => -- File too large

            raise Cada.Error.File_Too_Large with error_msg;

          when others =>

            declare

              errno_text : constant String := Cada.Error.get_error_message(error_code);

            begin

              raise Cada.Error.Unknown_Error with errno_text & ": " & error_msg;

            end;

        end case;

      end;

    end if;

    return Natural (bytes_written);

  end write;


  function duplicate (self : in Object) return Object is

    new_fd : constant File_Descriptor :=

      File_Descriptor (unistd_h.dup (Interfaces.C.Int (self.fd)));

  begin

    if new_fd = -1 then

      declare

        error_code : constant Interfaces.C.int := Cada.Error.get_errno;

        error_msg  : constant String           :=

          "dup(2) failed for fd " & self.fd'image &

          " (errno: " & error_code'image & ")";

      begin

        case error_code is

          when errno_h.EBADF =>   -- Bad file descriptor

            raise Cada.Error.Bad_File_Descriptor with error_msg;

          when errno_h.EINTR =>   -- Interrupted system call

            raise Cada.Error.Interrupted_System_Call with error_msg;

          when errno_h.EMFILE =>  -- Per-process limit on open file descriptors reached

            raise Cada.Error.Too_Many_Open_Files with error_msg;

          when others =>

            declare

              errno_text : constant String := Cada.Error.get_error_message(error_code);

            begin

              raise Cada.Error.Unknown_Error with errno_text & ": " & error_msg;

            end;

        end case;

      end;

    end if;


    return (Ada.Finalization.Controlled with fd => new_fd);

  end duplicate;


  function duplicate_to (self   : in Object;

                         new_fd : File_Descriptor)

    return Object is

    result_fd : constant File_Descriptor :=

      File_Descriptor (unistd_h.dup2 (Interfaces.C.Int (self.fd),

                                      Interfaces.C.Int (new_fd)));

  begin

    if result_fd = -1 then

      declare

        error_code : constant Interfaces.C.int := Cada.Error.get_errno;

        error_msg  : constant String           :=

          "dup2(2) failed for old_fd " & self.fd'image & " to new_fd " &

          new_fd'image & " (errno: " & error_code'image & ")";

      begin

        case error_code is

          when errno_h.EBADF => -- Bad file descriptor

            raise Cada.Error.Bad_File_Descriptor with error_msg;

          when errno_h.EINTR => -- Interrupted system call

            raise Cada.Error.Interrupted_System_Call with error_msg;

          when errno_h.EBUSY => -- (Linux-specific) Race condition detected

            raise Cada.Error.Device_Busy with error_msg;

          when others =>

            declare

              errno_text : constant String := Cada.Error.get_error_message(error_code);

            begin

              raise Cada.Error.Unknown_Error with errno_text & ": " & error_msg;

            end;

        end case;

      end;

    end if;


    return (Ada.Finalization.Controlled with fd => result_fd);

  end duplicate_to;


  function umask (new_mask : Cada.Types.File_Mode)

    return Cada.Types.File_Mode is

    mode : constant sys_types_h.mode_t :=

      sys_stat_h.umask (sys_types_h.mode_t (new_mask));

  begin

    return Cada.Types.File_Mode (mode);

  end umask;


  overriding

  procedure finalize (self : in out Object) is

  begin

    if self.fd /= -1 then

      -- finalize에서는 예외를 전파하지 않는 것이 좋으므로,

      -- 오류 발생 가능성이 있는 호출은 블록으로 감쌉니다.

      declare

        result : Interfaces.C.Int :=

          unistd_h.close (Interfaces.C.Int (self.fd));

      begin

        if result /= 0 then

           null; -- 오류를 무시하거나 내부 로그로 기록

        end if;

      end;

      self.fd := -1;

    end if;

  end finalize;


end Cada.File;

추천 비추천

1

고정닉 0

0

댓글 영역

전체 댓글 0
본문 보기

하단 갤러리 리스트 영역

왼쪽 컨텐츠 영역

갤러리 리스트 영역

갤러리 리스트
번호 제목 글쓴이 작성일 조회 추천
설문 반응이 재밌어서 자꾸만 놀리고 싶은 리액션 좋은 스타는? 운영자 25/07/28 - -
AD 휴대폰 액세서리 세일 중임! 운영자 25/07/28 - -
공지 프로그래밍 갤러리 이용 안내 [92] 운영자 20.09.28 45986 65
2877445 [사설]13년 만에 FTA 사실상 폐기 발명도둑잡기(118.216) 19:43 6 0
2877444 모든게 원망스럽다 ㅇㅇ(118.235) 19:39 6 0
2877443 모든 것에 잘못에는 개개인의 책임이 크다. 넥도리아(220.74) 19:37 6 0
2877442 내가 사라져도 세상은 돌아가겠지. [6] 프갤러(220.84) 19:22 21 0
2877441 결혼생각 있으면 꼭 봐라 싱글벙글(222.105) 19:18 12 0
2877440 배급견 문학 공모전 전국 거지 총집결 ♥님아그다리를건너지마오쩌둥♥갤로그로 이동합니다. 19:11 14 0
2877439 롤 대회 미니언은 방어력 더 약함 ㅇㅅㅇ?? 왤캐 잘죽음 ㅇㅇ(223.39) 19:09 8 0
2877438 ■노베이스가 게시판 만드려면 기간 대충 얼마나 잡아야할까요? [1] ㅇㅇ갤로그로 이동합니다. 19:08 27 0
2877437 러빨러는 왜 러스트 개발 관련글 안 씀?? [1] 나르시갤로그로 이동합니다. 18:56 20 0
2877436 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥님아그다리를건너지마오쩌둥♥갤로그로 이동합니다. 18:53 10 0
2877435 혁신인가, 부채 늘리는 지름길인가…스테이블코인이 뭐길래 발명도둑잡기(118.216) 18:39 12 0
2877434 나님 끙야즁 ♥님아그다리를건너지마오쩌둥♥갤로그로 이동합니다. 18:33 12 0
2877433 영혼에 비수가 꽂혀 심정지 상태입니다. 프갤러(220.84) 18:32 15 0
2877432 결혼생각 있으면 꼭 봐라 싱글벙글(222.105) 18:18 20 0
2877431 안정환 “경기 도중 똥싼 적 있어···꽤 많아” (가보자고) 발명도둑잡기(118.216) 17:58 19 0
2877430 ■취업할려면 스프링과 스프링부트 중 뭘 파야하나요? [3] ㅇㅇ갤로그로 이동합니다. 17:55 48 0
2877429 오늘 해킹 공부하면서 배운 것 루도그담당(58.239) 17:53 35 0
2877428 글로벌 ‘나는 가수다’ 탄생 임박? 발명도둑잡기(118.216) 17:45 15 0
2877426 좀 있으면 절기상 가을입니당 ♥님아그다리를건너지마오쩌둥♥갤로그로 이동합니다. 17:43 19 0
2877425 겜만들어서 세금 3300낸다는대 [2] 프갤러(211.235) 17:38 31 0
2877424 나를 죽으라고 포악하게 몰아세웠지???? 프갤러(220.84) 17:27 22 0
2877423 교정 때문에 아이스크림 먹을 때 이가 아프다 발명도둑잡기(118.216) 17:22 14 0
2877422 오늘의 영상 기획 실마리: 도서관, 종교시설, 영안실에서 음악 공연 발명도둑잡기(118.216) 17:16 13 0
2877421 넥도리아 안철수 댓글에 달았습니다. 뒷골목 간담회 넥도리아(220.74) 17:16 16 0
2877420 와.. ㅅㅂ 김정은 사망..존시나모롤 [2] ♥님아그다리를건너지마오쩌둥♥갤로그로 이동합니다. 17:13 48 0
2877419 개발자도 이제는 인싸 직업임 [2] 어린이노무현갤로그로 이동합니다. 17:12 53 0
2877418 aa 프갤러(113.59) 17:02 17 0
2877417 ㅇㅇ 프갤러(113.59) 17:01 18 0
2877416 무더운 여름 <버닝> 발명도둑잡기(118.216) 16:55 13 0
2877415 해외에서도 아이피따서 해킹하는거 쉽냐 [1] ㅇㅇ(106.101) 16:46 31 0
2877414 내가 느끼는게 일단 지금 잘 돌아가는거 사실 구조 바꾸고 리팩토링해야하데 ㅆㅇㅆ(124.216) 16:45 30 0
2877413 가끔 보면 나는 프로그래밍에 재능이 없는거 같아 [4] ㅆㅇㅆ(124.216) 16:38 54 0
2877412 사담콘 다녀와씀 [6] 어린이노무현갤로그로 이동합니다. 16:37 53 0
2877411 내가 만든 mcp 나름 성능좋은거같은데 [2] ㅆㅇㅆ찡갤로그로 이동합니다. 16:32 34 0
2877410 추악하게 거듭나기전에 좋게좋게 합시다. 프갤러(220.84) 16:31 16 0
2877408 월급이 3번 나오는 삶… [3] 어린이노무현갤로그로 이동합니다. 16:20 42 0
2877407 제품번호를 277 이 아닌 원래 227이여야 하는데, [1] 넥도리아(220.74) 16:19 21 0
2877406 KT 유튜브프리미엄 할인 어떻게 되냐 [2] 프갤러(125.243) 16:16 23 0
2877405 한컴 회장님 저 이 옵션에 접근했어요... 넥도리아(220.74) 16:09 22 0
2877404 쓰레기같이 연명하기싫어요. 프갤러(220.84) 16:09 24 0
2877403 나는 스스로 쓰레기인거 인증하고 남한테 말할 자신있음 [1] 뒷통수한방(1.213) 16:01 37 0
2877402 안창호 인권위원장 즉각 사퇴하라! 발명도둑잡기(118.216) 15:54 13 0
2877401 숲 속 와인 축제 발명도둑잡기(118.216) 15:51 18 0
2877400 무직 백수들 이런 폭염에 야외노가다 상하차 시켜야지 류류(121.160) 15:45 23 0
2877399 요리사 힘든 이유 [1] 발명도둑잡기(118.216) 15:44 27 0
2877398 더워질수록 혐오와 살인사건이 늘어난다 발명도둑잡기(118.216) 15:41 16 0
2877397 리누스 토르발스 성이 북유럽 신 토르에서 나왔다네 [1] 발명도둑잡기(118.216) 15:39 20 0
2877396 포인터 얘기가 나와서 말인데 나르시갤로그로 이동합니다. 15:26 27 0
2877394 cmd에서 빌드실행 하는데 왜 이러나요? [3] 프갤러(218.149) 15:22 36 0
뉴스 톰 크루즈, 26세 연하 여배우와 공개 열애 디시트렌드 08.01
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2