2011-03-07 2 views
19

쓰기 용으로 파일을 열고 싶지만 아직 존재하지 않는 경우에만 엽니 다. 파일이 있으면 예외를 발생시키고 싶습니다. 이것을하는 것이 최선의 방법입니까?루비에 파일이없는 경우에만 파일을 쓰기 위해 엽니 다.

filename = 'foo' 
raise if File.exists? filename 
File.open(filename, 'w') do |file| 
    file.write contents 
end 

경쟁 조건없이이 작업을 수행하는 가장 관용적 인 방법은 무엇입니까?

답변

29

추가 조사를 한 후에 File :: CREAT 및 File :: EXCL 모드 플래그를 사용할 수 있습니다.

filename = 'foo' 
File.open(filename, File::WRONLY|File::CREAT|File::EXCL) do |file| 
    file.write contents 
end 

이 경우 open은 파일이 존재하면 예외를 발생시킵니다. 한 번 실행하면이 프로그램은 오류없이 성공하고 foo이라는 파일을 만듭니다.

foo.rb:2:in `initialize': File exists - foo (Errno::EEXIST) 
    from foo.rb:2:in `open' 
    from foo.rb:2 

man open에서 :

 O_WRONLY  open for writing only 
     O_CREAT   create file if it does not exist 
     O_EXCL   error if O_CREAT and the file exists 
두 번째 실행에서 프로그램이 방출
관련 문제