]>
git.p6c8.net - devedit.git/blob - modules/File/Access.pm
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-02-10
23 use base
qw(Exporter);
37 # Check if flock() is available
38 # I found this piece of code somewhere in the internet
40 $has_flock = eval { local $SIG{'__DIE__'}; flock(STDOUT
,0); 1 };
44 # Collect the files and directories in a directory
48 # Return: Hash reference: dirs => directories
56 return unless(-d
$dir);
58 # Get all the entries in the directory
60 opendir(DIR
,$dir) or return;
61 my @entries = readdir(DIR
);
62 closedir(DIR
) or return;
66 @entries = sort {uc($a) cmp uc($b)} @entries;
71 foreach my $entry(@entries)
73 next if($entry eq '.' || $entry eq '..');
75 if(-d
$dir.'/'.$entry)
85 return {dirs
=> \
@dirs, files
=> \
@files};
90 # Create a file, but only if it doesn't already exist
92 # (I wanted to use O_EXCL for this, but `perldoc -f sysopen`
93 # doesn't say that it is available on every system - so I
94 # created this workaround using O_RDONLY and O_CREAT)
96 # Params: File to create
98 # Return: true on success;
99 # false on error or if the file already exists
108 sysopen(FILE
,$file,O_RDONLY
| O_CREAT
) or return;
109 close(FILE
) or return;
116 # System independent wrapper function for flock()
117 # On systems where flock() is not available, this function
118 # always returns true.
120 # Params: 1. Filehandle
123 # Return: Status code (Boolean)
127 my ($handle,$mode) = @_;
129 return 1 unless($has_flock);
130 return flock($handle,$mode);
135 # Read out a file completely
138 # 2. true => open in binary mode
139 # false => open in normal mode (default)
141 # Return: Contents of the file (Scalar Reference)
145 my ($file,$binary) = @_;
148 sysopen(FILE
,$file,O_RDONLY
) or return;
149 file_lock
(FILE
,LOCK_SH
) or do { close(FILE
); return };
150 binmode(FILE
) if($binary);
152 read(FILE
, my $content, -s
$file);
154 file_lock
(FILE
,LOCK_UN
) or do { close(FILE
); return };
155 close(FILE
) or return;
165 # 2. File content as Scalar Reference
166 # 3. true => open in binary mode
167 # false => open in normal mode (default)
169 # Return: Status code (Boolean)
173 my ($file,$content,$binary) = @_;
176 sysopen(FILE
,$file,O_WRONLY
| O_CREAT
| O_TRUNC
) or return;
177 file_lock
(FILE
,LOCK_EX
) or do { close(FILE
); return };
178 binmode(FILE
) if($binary);
180 print FILE
$$content or do { close(FILE
); return };
182 file_lock
(FILE
,LOCK_UN
) or do { close(FILE
); return };
183 close(FILE
) or return;
190 # Remove a file from the list of files in use
192 # Params: 1. File::UseList object
195 # Return: Status code (Boolean)
199 my ($uselist,$file) = @_;
201 $uselist->remove_file($file) or return;
202 $uselist->save or return;
207 # it's true, baby ;-)
patrick-canterino.de