디시인사이드 갤러리

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

갤러리 본문 영역

Ada 코드 다시..

나르시갤로그로 이동합니다. 2025.07.22 23:58:25
조회 35 추천 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/21 - -
2874002 태연 ㅇㅅㅇ 헤르 미온느갤로그로 이동합니다. 07.24 26 0
2874000 하루 한 번 헤르미온느 찬양 헤르 미온느갤로그로 이동합니다. 07.24 38 0
2873998 흠냐흠냐 딱몽(61.253) 07.24 33 0
2873990 REDUX 스타일 UDF 공부하고 있는데 왜 REDUX 스타일 [1] ㅆㅇㅆ(124.216) 07.24 50 0
2873987 궁금한게 남이 만든 코드 내가 긴빠이쳐서 나혼자만 쓰면 안되냐? [2] ㅆㅇㅆ(124.216) 07.24 85 0
2873985 오늘 중으로 Clair.Signal 끝나겠지. 나르시갤로그로 이동합니다. 07.24 34 0
2873981 택시 업계가 어떻게 유지되는지 의문임 (궁금증) [1] 야옹아저씨갤로그로 이동합니다. 07.24 73 1
2873979 나는 왜 낮보다 밤이 좋을까 [2] ㅆㅇㅆ(124.216) 07.24 51 0
2873978 ai한테 설계를 맡기면 안됨 [6] 공기역학갤로그로 이동합니다. 07.24 97 0
2873976 이거좀 알려주세요 형님들 궁금해뒤질것같아요 [2] ㅇㅇ(38.72) 07.24 58 0
2873974 나쁜 모바일신분증 반대 ㅇㅇ갤로그로 이동합니다. 07.24 48 0
2873972 공공와이파이 중에 1Gbps 넘는게 있을까 ㅇㅇ(110.10) 07.24 34 0
2873970 예전글들을 봤는데 [5] 개멍청한유라갤로그로 이동합니다. 07.24 92 0
2873969 코파일럿 모델 보통 뭐쓰시나요?? 프갤러(221.151) 07.24 55 0
2873967 하루에 한줄 감사의 코딩 공기역학갤로그로 이동합니다. 07.24 62 0
2873965 아싸 드디어 Clair.Signal 설계 완료. 나르시갤로그로 이동합니다. 07.24 39 0
2873963 인생이 노력이 아니면 새로운 기적을 알려줌 뒷통수한방(1.213) 07.23 36 0
2873962 기적만을 바라봅니다.. 손발이시립디다갤로그로 이동합니다. 07.23 54 0
2873961 더이상 개선될 기미가 안보임 ㅇㅅㅇ 손발이시립디다갤로그로 이동합니다. 07.23 59 0
2873960 문재인 아들은 예술가아니엿나? [2] 밀우갤로그로 이동합니다. 07.23 55 0
2873959 공수처 검찰청 경찰청 국제수사 과학수사 포랜식수사 기무사 국정원 존재이유 뒷통수한방(1.213) 07.23 36 0
2873958 공부량이라고 하면 중3때가 피크를 쳤던 기억이 남 ㅇㅅㅇ 손발이시립디다갤로그로 이동합니다. 07.23 32 0
2873956 방통대에 다니려면 매일 최소 2시간의 독학은 해줘야 하는데 손발이시립디다갤로그로 이동합니다. 07.23 60 0
2873955 클로드 파일 시스템 좆병신같아서 fastMCP써서 만들었는데 ㅆㅇㅆ(124.216) 07.23 64 0
2873953 분기점이 생기기 전에 더 알찬 삶을 살았더라면 하는 후회가 막심하다 손발이시립디다갤로그로 이동합니다. 07.23 46 0
2873952 [C언어] 안전한 시그널 처리: Self-Pipe Trick [1] 나르시갤로그로 이동합니다. 07.23 61 0
2873951 인생에 또다른 분기점이 있는데 손발이시립디다갤로그로 이동합니다. 07.23 44 0
2873950 아스카님 음해 멈춰주십시오. 모쏠아다 비전공 지잡 다 팩트인데 [2] ㅆㅇㅆ(124.216) 07.23 63 0
2873949 과거가 너무나 그립다 손발이시립디다갤로그로 이동합니다. 07.23 38 0
2873948 내가 백수라니 200버니까 백수 아님 [1] ㅆㅇㅆ(124.216) 07.23 75 0
2873947 알고리즘과 알고리듬 표기법에 관련된 이야기- [1] 프갤러(121.172) 07.23 51 0
2873946 우울증에 걸리면 우울한게 주요하지만 관심사에 대한 흥미를 잃는 것도 참 손발이시립디다갤로그로 이동합니다. 07.23 40 0
2873945 알고리즘? 프갤러(121.172) 07.23 55 0
2873944 알고리듬 PS 손놓은 지가 10주년이 되었다 [4] 손발이시립디다갤로그로 이동합니다. 07.23 66 0
2873943 새로 만들고 있는 Rx TextEngine 프갤러(121.172) 07.23 50 0
2873942 요즘 공부 안하고 [4] 류도그담당(58.239) 07.23 71 0
2873941 코딩 질문에 대한 답변 - 라노벨 연합에 가입하셈 [2] 프갤러(121.172) 07.23 46 0
2873940 취업갤을 가보면 가끔 컴공출신이라는 것들이 문과충들 사이에 보이는데 손발이시립디다갤로그로 이동합니다. 07.23 97 0
2873938 창원 비아이엠솔루션 아는 사람있냐 프갤러(121.151) 07.23 23 0
2873936 코딩 질문이있습니다. [20] 프갤러(121.157) 07.23 94 0
2873935 뉴프로는 뭐임? [1] 프갤러(121.172) 07.23 58 0
2873934 모바일신분증으로 온라인에서도 본인인증 가능함? [1] ㅇㅇ(121.148) 07.23 41 0
2873932 공수처 검찰청 경찰청 국제수사 과학수사 포랜식수사 기무사 국정원 존재이유 [1] 뒷통수한방(1.213) 07.23 25 0
2873931 라노벨 작가 갤러리 뭐냐. 프갤러(121.172) 07.23 37 0
2873929 [애니뉴스] 끼마귀 처형자 - 스토리 두 개 중 하나 추천받음 프갤러(121.172) 07.23 21 0
2873927 ㅆㅇㅆ의 제자가 되고 싶다 [5] 아스카영원히사랑해갤로그로 이동합니다. 07.23 79 0
2873925 서울gook들은 지들 주제를 모르나 ???? 프갤러(221.142) 07.23 38 0
2873924 1억이 좆으로 보이냐??!! [4] 아스카영원히사랑해갤로그로 이동합니다. 07.23 86 0
2873922 궁금한게 루비는 여기서 정병 도배해봤자 남는게 없을텐데 [1] ㅆㅇㅆ(124.216) 07.23 29 0
2873918 삼성카드앱 웹뷰냐..? [4] 하아얀갤로그로 이동합니다. 07.23 101 0
뉴스 배우 김윤석, HB엔터테인먼트와 전속계약 체결! 차기 행보에 관심 집중 디시트렌드 07.24
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2