디시인사이드 갤러리

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

갤러리 본문 영역

Ada 코드 다시..

나르시갤로그로 이동합니다. 2025.07.22 23:58:25
조회 55 추천 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/08/04 - -
2878068 컴퓨터는 변하지만 계산은 변하지 않는다는점만 봐도 컴공은 컴퓨터에 대한 [2] ㅆㅇㅆ(124.216) 08.04 80 3
2878067 ip바꿔서 신분세탁 해야하는데 프갤러(121.139) 08.04 21 0
2878065 코딩 취미로 할만한가요 [6] 프갤러(211.192) 08.04 67 0
2878064 빛 좋은 개살구여선 안됐어. 프갤러(220.84) 08.04 32 0
2878063 장애인 새끼들 프갤러(121.139) 08.04 28 1
2878062 gpt 정신나갔노? [2] 프갤러(113.59) 08.04 49 0
2878060 당장 트랜지스터, CPU 아키텍쳐 몰라도 너네 코딩 할 수 있잖아 ㅆㅇㅆ(124.216) 08.04 30 0
2878058 컴공을 한다는 애들이 컴퓨터 구조에만 집착하는건 본질을 못보는거임 [2] ㅆㅇㅆ(124.216) 08.04 89 0
2878057 코딩알못 문과인데 파이썬이 왜 최적화가 구린 언어라는건가요 [2] 프갤러(211.192) 08.04 48 0
2878054 무료급식소를 차려서 고통을 나누어보아요. 프갤러(220.84) 08.04 22 0
2878053 ai챗봇 대화하는데 매번 똑같은말만하고 이상한링크 2개로 헛소리하는데 뒷통수한방(1.213) 08.04 22 0
2878052 보안이 인기가 많았던적이 없다는게 사실입니까 [1] 뒷통수한방(1.213) 08.04 59 0
2878051 컴퓨터 과학은 컴퓨터에 대한 학문이 아니야. [3] ㅆㅇㅆ(124.216) 08.04 60 2
2878049 cs 배우면 머하냐? 프갤러(121.139) 08.04 39 2
2878048 범죄자 인권챙기는건 좌파의 악행이니 뭐니 하더만 손발이시립디다갤로그로 이동합니다. 08.04 29 0
2878047 남자가 근육질 남자 보고 좋아하면 동성애 성향 있는건가 발명도둑잡기갤로그로 이동합니다. 08.04 21 0
2878044 우주문명과 통신 편지 ♥꽃보다냥덩♥갤로그로 이동합니다. 08.04 17 0
2878043 아이러니하게 컴공은 컴퓨터 구조를 깊게 이해할수록 프로그래밍이 어려움 [4] ㅆㅇㅆ(124.216) 08.04 80 0
2878042 째깍째깍째깍 마귀의 소굴을 채우는 시곗소리. 프갤러(220.84) 08.04 21 0
2878041 한국 가수 노래가 미국이나 외국에서 뜨려면 영어 가사가 유리한가 연구 발명도둑잡기갤로그로 이동합니다. 08.04 31 0
2878038 나님 주무시기전 소통⭐+ 질문 받음 [1] ♥꽃보다냥덩♥갤로그로 이동합니다. 08.04 30 0
2878037 추억 속의 사람이 그리워요. 프갤러(220.84) 08.04 33 0
2878034 언론에서 아이폰이 안전하다고 오보하면 절대 안되는 이유 발명도둑잡기갤로그로 이동합니다. 08.04 42 0
2878033 흐으음 2가지 제안 받음 [2] 어린이노무현갤로그로 이동합니다. 08.04 57 0
2878031 10cm-사랑은 여섯줄 ㅇㅇ(14.52) 08.04 28 0
2878028 전세계 공유기 보안기술 취약점 문제 발명도둑잡기갤로그로 이동합니다. 08.04 33 0
2878026 마귀를 가둔 봉인 부적의 효력도 떨어져가. 프갤러(220.84) 08.04 22 0
2878025 벌써 10시넹.. ♥꽃보다냥덩♥갤로그로 이동합니다. 08.04 18 0
2878023 아 근데 난 왜 이렇게 멍청할까 [4] 루도그담당(58.239) 08.04 61 0
2878020 마귀의 웅덩이에 태어나고싶지않았어. 프갤러(220.84) 08.04 22 0
2878017 아니 근데 신기하네 2차 보안 휴대폰 보안까지했는데 어떻게 [5] ㅆㅇㅆ(124.216) 08.04 54 0
2878015 인생 다 산 기분 든다는 힙합 갤러리 사용 발명도둑잡기갤로그로 이동합니다. 08.04 22 0
2878014 커서 IDE 생각보다 많이 실망이네 [1] 프갤러(211.235) 08.04 38 0
2878011 마귀의 집을 지키기도 지겹습니다. 프갤러(220.84) 08.04 26 0
2878010 기본적인 보안도 못지키는 빡통은 개발자하면 안됨 ㅇㅇ(211.234) 08.04 39 2
2878009 랜선에서 나온 작은거 재활용 어디다 버림? 넥도리아(119.195) 08.04 21 0
2878007 해커는 도둑놈인데 인기가 있을까 ㄹㅇ 도둑노무 새끼들 [2] ㅆㅇㅆ(124.216) 08.04 37 0
2878005 106.101 빛섬 광고 혹시 간첩인가? 발명도둑잡기갤로그로 이동합니다. 08.04 21 0
2878004 나님 일본에서 초고교급 여고생 만난썰 ♥꽃보다냥덩♥갤로그로 이동합니다. 08.04 24 0
2878001 추악한 썩은 시체처럼 살아서 미안해요. 프갤러(220.84) 08.04 23 0
2878000 드라마 <아이쇼핑> 한대서 생각나는 것 발명도둑잡기갤로그로 이동합니다. 08.04 31 0
2877997 우리 둘째 작은 할아버지가 대학생 때 럭비선수였는데 발명도둑잡기갤로그로 이동합니다. 08.04 27 0
2877995 지원금2 시작 ㅇㅇ(106.101) 08.04 31 0
2877994 헉! 나님 간택 받은듯? ♥꽃보다냥덩♥갤로그로 이동합니다. 08.04 28 0
2877990 세상의 무게에 짓눌려 터지는 가엾은 영혼을 보세요. 프갤러(220.84) 08.04 26 0
2877988 여행나가면 뭐해야함?? 미리 이것저것 알아보고 가야하나 ㅇㅇ(223.39) 08.04 20 0
2877986 기껏 열심히 보안공부해봤자 대부분이 관제 엔딩아님?? 타이밍뒷통수한방(1.213) 08.04 40 0
2877984 예전에도 말했듯이 디씨인싸이드 프로그래밍 갤러리는 각국 정보기관이 발명도둑잡기갤로그로 이동합니다. 08.04 27 0
2877981 한남혐오 멍유의 산뜻한 아침❤+ [1] ♥꽃보다냥덩♥갤로그로 이동합니다. 08.04 35 0
2877980 20분 전에 필라이트 맥주 한 잔 마셨다 발명도둑잡기갤로그로 이동합니다. 08.04 46 0
뉴스 웨이브투어스, 美 최대 음악 축제 '롤라팔루자' 무대 성료…열광적 분위기 '눈길' 디시트렌드 18:00
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2