디시인사이드 갤러리

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

갤러리 본문 영역

Ada 코드 다시..

나르시갤로그로 이동합니다. 2025.07.22 23:58:25
조회 56 추천 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 - -
공지 프로그래밍 갤러리 이용 안내 [92] 운영자 20.09.28 46089 65
2878619 문돌이 블록코딩 할만함? [1] 프갤러(220.95) 11:18 6 0
2878618 아 안해 루도그담당(211.184) 11:18 7 0
2878617 금융에서 사용하는 DDD프레임워크는 진짜 쓰레기다 [2] 밀우갤로그로 이동합니다. 11:14 12 0
2878616 SI/SM이 왜 저평가 받겠냐 도메인 축적의 차이임 ㅆㅇㅆ(124.216) 11:05 27 0
2878615 힙에서 call 하는거 구현하고 있는데 [4] 루도그담당(211.184) 11:04 29 0
2878614 개발이 재미있냐 진심? [1] 프갤러(118.235) 11:03 21 0
2878613 틀리앙쪽이 도메인 지식 천국임. ㅆㅇㅆ(124.216) 10:59 11 0
2878612 어미, 아비를 팔아먹은 모계/부계 친족의 죄도 물어야 하렵니까? 프갤러(220.84) 10:53 11 0
2878611 보안 전망 좋지 않나 프갤러(118.235) 10:53 14 0
2878609 당장 00년대 소니 기기 가격대 보면 그걸 다룰 수있단거 자체가 [4] ㅆㅇㅆ(124.216) 10:49 20 0
2878608 틀리앙이 개발 잘 알수밖에 없음 이유가 00년대 초반에 IT붐떄 ㅆㅇㅆ(124.216) 10:42 22 0
2878607 자장가 올러줄게 ㅇㅇ(49.165) 10:25 16 0
2878606 애비새끼가 외모, 지능, 재력, 능력 볼품없는 점부터 시작이었어요. 프갤러(220.84) 10:19 17 0
2878605 나님 끙야&쉬야즁❤+ ♥꽃보다냥덩♥갤로그로 이동합니다. 09:56 14 0
2878603 핵심이 마귀면 안됐어요. 프갤러(220.84) 09:32 29 0
2878602 어제 개인 프로그래밍 못하고 정신없이 잤어 [1] 프갤러(218.154) 09:18 37 0
2878601 근 1달동안 하루에 1시간씩 MSDN 읽기하고 있는데 [2] ㅆㅇㅆ(124.216) 09:18 36 0
2878599 넌 다리 밑에서 주워왔어..ㅇㅅㅇ 헤르 미온느갤로그로 이동합니다. 09:14 24 0
2878598 태연 ㅇㅅㅇ 헤르 미온느갤로그로 이동합니다. 09:12 16 0
2878597 하루 한 번 헤르미온느 찬양 헤르 미온느갤로그로 이동합니다. 09:11 17 0
2878596 되지않을 환경에 출생시킨 것부터 지옥이었어요. 프갤러(220.84) 09:02 19 0
2878595 그냥 공부만 계속하고싶다 [5] 밀우갤로그로 이동합니다. 09:01 44 0
2878594 경력이나 존나쌓다 공기업이나 지원해야지 [3] ㅇㅇ갤로그로 이동합니다. 08:55 42 0
2878591 소중한 사람 못 알아 보고 근시안으로 짤라 버리고 소중한줄 알지. 프갤러(59.16) 08:05 21 0
2878588 나의 존재는 모순적입니다. 융화할 수 없겠습니다. 프갤러(220.84) 07:40 22 0
2878587 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥꽃보다냥덩♥갤로그로 이동합니다. 07:40 16 0
2878585 프로그래머 뭐하러 하냐? 할필요 없다. 최저임금. 프갤러(59.16) 07:26 29 0
2878584 하루에 한문자 감사의 코딩 [1] 공기역학갤로그로 이동합니다. 07:08 43 0
2878578 나 쇼핑몰 이용 많이했는데 디자이너들 보니까 [1] ㅇㅇ(49.1) 03:32 52 0
2878575 일본 업계는 코틀린 언급조차도 없네 [1] 프갤러(220.92) 03:02 100 0
2878571 컴퓨터 = 난로 뒷통수한방(1.213) 02:11 38 0
2878570 음기 충전 발명도둑잡기갤로그로 이동합니다. 02:10 27 0
2878569 DJ가 일찌감치 일본의 우경화를 예언한 근거는? 발명도둑잡기갤로그로 이동합니다. 01:38 26 0
2878566 지치고 힘든 너에게 해주고싶은 말 믕믕이갤로그로 이동합니다. 01:14 34 0
2878564 박효신이 직접 밝히는 노래 잘하는 방법 발명도둑잡기갤로그로 이동합니다. 01:05 29 0
2878563 실시간베스트 만화 "텔레비전" 보니 생각나는 예전 글 발명도둑잡기갤로그로 이동합니다. 01:01 16 0
2878562 故 이선균·송영규 나란히…고은별 "또 하나의 별이 지다" 발명도둑잡기갤로그로 이동합니다. 00:52 28 0
2878561 <착한 사나이> 한대서 생각나는 예전 글 발명도둑잡기갤로그로 이동합니다. 00:34 30 0
2878560 행동력이 없단 이유로 겪은 모진 핍박 프갤러(220.84) 00:23 34 0
2878558 틀리앙이 아마 프로그래밍 사이트중 수준은 젤 높을껄 [6] ㅆㅇㅆ(124.216) 08.05 83 0
2878557 rvizweb 써본 사람 있냐 ? 프갤러(211.217) 08.05 27 0
2878555 어쩔수없을 것이면 앞당겼어야 했겠지요. 프갤러(220.84) 08.05 31 0
2878554 "사랑은 움직이는 거야" 광고 보면 생각나는 예전 글 발명도둑잡기갤로그로 이동합니다. 08.05 29 0
2878553 장대호도 일베충이여서 숙청당한거임?? 뒷통수한방(1.213) 08.05 26 0
2878552 일베충들 왜 욕먹는거임 커뮤니티가 그렇개 많은데 뒷통수한방(1.213) 08.05 22 0
2878551 면목이 없으나 어쩔수없는 일이예요. 프갤러(220.84) 08.05 24 0
2878550 클리앙 vs okky 어디가 더 강하냐?? [1] 프갤러(1.213) 08.05 55 0
2878549 내가 잘 모르는 분야 발명도둑잡기갤로그로 이동합니다. 08.05 30 0
2878548 나는 프로그래밍에 재능없단 생각 항상 한다 [6] ㅆㅇㅆ(124.216) 08.05 98 0
뉴스 '좀비딸' 개봉 6일 만에 200만 관객 돌파 디시트렌드 08.05
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2