]>
git.p6c8.net - devedit.git/blob - modules/File/Access.pm
70a1c04a33257c53b0f2e9b3c588f202f441d8dd
4 # Dev-Editor - Module File::Access
6 # Some simple routines for doing things with files by
7 # using only one command
9 # Author: Patrick Canterino <patrick@patshaping.de>
10 # Last modified: 2005-04-09
23 use base
qw(Exporter);
36 # Check if flock() is available
37 # I found this piece of code somewhere in the internet
39 $has_flock = eval { local $SIG{'__DIE__'}; flock(STDOUT
,0); 1 };
43 # Collect the files and directories in a directory
47 # Return: Hash reference: dirs => directories
48 # files => files and symbolic links
55 return unless(-d
$dir);
57 # Get all the entries in the directory
59 opendir(DIR
,$dir) or return;
60 my @entries = readdir(DIR
);
61 closedir(DIR
) or return;
65 @entries = sort {uc($a) cmp uc($b)} @entries;
70 foreach my $entry(@entries)
72 next if($entry eq '.' || $entry eq '..');
74 if(-d
$dir.'/'.$entry && not -l
$dir.'/'.$entry)
84 return {dirs
=> \
@dirs, files
=> \
@files};
89 # Create a file, but only if it doesn't already exist
91 # (I wanted to use O_EXCL for this, but `perldoc -f sysopen`
92 # doesn't say that it is available on every system - so I
93 # created this workaround using O_RDONLY and O_CREAT)
95 # Params: File to create
97 # Return: true on success;
98 # false on error or if the file already exists
107 sysopen(FILE
,$file,O_RDONLY
| O_CREAT
) or return;
108 close(FILE
) or return;
115 # System independent wrapper function for flock()
116 # On systems where flock() is not available, this function
117 # always returns true.
119 # Params: 1. Filehandle
122 # Return: Status code (Boolean)
126 my ($handle,$mode) = @_;
128 return 1 unless($has_flock);
129 return flock($handle,$mode);
134 # Read out a file completely
137 # 2. true => open in binary mode
138 # false => open in normal mode (default)
140 # Return: Contents of the file (Scalar Reference)
144 my ($file,$binary) = @_;
147 sysopen(FILE
,$file,O_RDONLY
) or return;
148 file_lock
(FILE
,LOCK_SH
) or do { close(FILE
); return };
149 binmode(FILE
) if($binary);
151 read(FILE
, my $content, -s
$file);
153 close(FILE
) or return;
163 # 2. File content as Scalar Reference
164 # 3. true => open in binary mode
165 # false => open in normal mode (default)
167 # Return: Status code (Boolean)
171 my ($file,$content,$binary) = @_;
174 sysopen(FILE
,$file,O_WRONLY
| O_CREAT
| O_TRUNC
) or return;
175 file_lock
(FILE
,LOCK_EX
) or do { close(FILE
); return };
176 binmode(FILE
) if($binary);
178 print FILE
$$content or do { close(FILE
); return };
180 close(FILE
) or return;
185 # it's true, baby ;-)
patrick-canterino.de