]>
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-16
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
49 # files => files and symbolic links
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 && not -l
$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 close(FILE
) or return;
164 # 2. File content as Scalar Reference
165 # 3. true => open in binary mode
166 # false => open in normal mode (default)
168 # Return: Status code (Boolean)
172 my ($file,$content,$binary) = @_;
175 sysopen(FILE
,$file,O_WRONLY
| O_CREAT
| O_TRUNC
) or return;
176 file_lock
(FILE
,LOCK_EX
) or do { close(FILE
); return };
177 binmode(FILE
) if($binary);
179 print FILE
$$content or do { close(FILE
); return };
181 close(FILE
) or return;
188 # Remove a file from the list of files in use
190 # Params: 1. File::UseList object
193 # Return: Status code (Boolean)
197 my ($uselist,$file) = @_;
199 $uselist->remove_file($file) or return;
200 $uselist->save or return;
205 # it's true, baby ;-)
patrick-canterino.de