Welcome to WebmasterWorld Guest from 54.147.212.98

Forum Moderators: coopster & jatar k & phranque

Message Too Old, No Replies

How to open/modify file in subdirectory?

   
3:04 pm on Aug 9, 2010 (gmt 0)



Hi,

I'm new to Perl and I'm having trouble opening a sub directory and then writing an output file to that directory. I have tried something like:

$path= "/dir1/dir2/";
$filename= "filename.str";
opendir(MYDIR, $path);
$the_infile = $filename;
$the_outfile = 'fixed_'.$filename;
#open infile, open outfile, write corrections to output file...
closedir(MYDIR);


but the output file does not show up. The program works fine when working in the current directory.

Any suggestions?
Thanks!
3:24 pm on Aug 9, 2010 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member



the opendir() and closedir() is useless because you're not doing anything with it. dirhandles are to read the content of a directory. To change into a directory, use chdir.

But for this task, you won't need that. Just open() the files with that pathname,
open(INFILE, '<', $path . $the_infile) || die $!;
open(OUTFILE, '>', $path . $the_outfile) || die $!;
4:00 pm on Aug 9, 2010 (gmt 0)



When doing this:

$i=1; #test
$file_in= $filename_list[$i];
$file_out = 'fixed_'.$filename_list[$i];
print "Input File: ", $file_in,"\n";
print "Modified File: ", $file_out,"\n";
$the_infile=$directory_list[$i] . $file_in;
$the_outfile=$directory_list[$i] . $file_out;
print "path in: ", $the_infile,"\n";
print "path out: ", $the_outfile,"\n";
open(INFILE, '<', $the_infile) || die $!;
open(OUTFILE, '>', $the_outfile) || die $!;


I get the output:

Input File: APSET1.turntable.5.str
Modified File: fixed_APSET1.turntable.5.str
path in: /dir1/dir2/APSET1.turntable.5.str
path out: /dir1/dir2/fixed_APSET1.turntable.5.str

No such file or directory at modify_structure.pl line 66.

The file DOES exist in that directory. I am running the program in the directory above dir1. Would that be the correct path syntax to get to the file?
4:07 pm on Aug 9, 2010 (gmt 0)



Ah, I just made the path


../current_dir/dir1/dir2/APSET1.turntable.5.str


and it worked. Is there a reason I must go up a directory and specify the path like this?
4:23 pm on Aug 9, 2010 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member



well yes, / at the beginning of the path means an absolute path in the local file system.
instead of ../current_dir/dir1... you could've said ./dir1..
2:26 am on Aug 12, 2010 (gmt 0)

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member



Right, in

$path = /dir1/dir2/

the / means to start at the server root, and those dirs are not there. Relative directory references will drive you nuts, when dealing with file structure use the full path, like /var/www/example.com/rir1/dir2/ or however your server's set up. Get the environment variables for your server, most likely you're looking for $ENV{'DOCUMENT_ROOT'}