]>
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-01-06
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
139 # Return: Contents of the file (Scalar Reference)
146 sysopen(FILE
,$file,O_RDONLY
) or return;
147 file_lock
(FILE
,LOCK_SH
) or do { close(FILE
); return };
149 read(FILE
, my $content, -s
$file);
151 file_lock
(FILE
,LOCK_UN
) or do { close(FILE
); return };
152 close(FILE
) or return;
162 # 2. File content as Scalar Reference
163 # 3. true => open in binary mode
164 # false => open in normal mode (default)
166 # Return: Status code (Boolean)
170 my ($file,$content,$binary) = @_;
173 sysopen(FILE
,$file,O_WRONLY
| O_CREAT
| O_TRUNC
) or return;
174 file_lock
(FILE
,LOCK_EX
) or do { close(FILE
); return };
175 binmode(FILE
) if($binary);
177 print FILE
$$content or do { close(FILE
); return };
179 file_lock
(FILE
,LOCK_UN
) or do { close(FILE
); return };
180 close(FILE
) or return;
187 # Remove a file from the list of files in use
189 # Params: 1. File::UseList object
196 my ($uselist,$file) = @_;
198 $uselist->remove_file($file);
204 # it's true, baby ;-)
patrick-canterino.de