Search Results

Search found 117 results on 5 pages for 'fh'.

Page 1/5 | 1 2 3 4 5  | Next Page >

  • explode is not working to split string

    - by pmms
    we unable to split the string following code.please Help us. <?php $i=0; $myFile = "testFile.txt"; $fh = fopen($myFile, 'a') or die("can't open file"); $stringData = "no\t"; fwrite($fh, $stringData); $stringData = "username \t"; fwrite($fh, $stringData); $stringData ="password \t"; fwrite ($fh,$stringData); $newline ="\r\n"; fwrite ($fh,$newline); $stringData1 = "1\t"; fwrite($fh, $stringData1); $stringData1 = "srinivas \t"; fwrite($fh, $stringData1); $stringData1 ="malayappa \t"; fwrite ($fh,$stringData1); fclose($fh); ?> $fh = fopen("testFile.txt", "r"); $ while (!feof($fh)) { $line = fgets($fh); echo $line; } fclose($fh); $Beatles = array('pmm','malayappa','sreenivas','PHP'); for($i=0;$i<count($Beatles);$i++) { if($i==2) { echo $Beatles[$i-1]; echo $Beatles[$i-2]; } } $pass_ar=array(); $fh = fopen("testFile.txt", "r"); while (!feof($fh)) { $line = fgets($fh); echo $line; $t1=explode(" ",$line); print_r($t1); array_push($pass_ar,t1); } fclose($fh); Thanks & Regards pmms

    Read the article

  • how to find the directory already is there or not in php

    - by zahir hussain
    hi i want know find the directory is already there or not... if not i would like to create the directory... my coding is below... $da = getdate(); $dat = $da["year"]."-".$da["mon"]."-".$da["mday"]; $m = md5($url)."xml"; if(is_dir($dat)) { chdir($dat); $fh = fopen($m, 'w'); fwrite($fh, $xml); fclose($fh); echo "yes"; } else { mkdir($dat,0777,true); chdir($dat); $fh = fopen($m, 'w'); fwrite($fh, $xml); fclose($fh); echo "not"; } thanks and advance

    Read the article

  • we are getting .txt file but not getting proper alignment

    - by pmms
    we are getting the following texfile_screenshot1.JPG when we are exporting data to .txt file we need output which is shown in texfile_screenshot2.JPG following is the code $myFile = "user_password.txt"; $fh = fopen($myFile, 'a') or die("can't open file"); $newline ="\r\n"; fwrite ($fh,$newline); $stringData1 = $_POST['uname1']." "." "." " ; fwrite($fh, $stringData1); $stringData1 =$_POST['password1']." "." "." "; fwrite($fh,$stringData1); $stringData1 = $_POST['email1']." "." "." "; fwrite($fh, $stringData1); fclose($fh);

    Read the article

  • Automatically release resources RAII-style in Perl

    - by Philip Potter
    Say I have a resource (e.g. a filehandle or network socket) which has to be freed: open my $fh, "<", "filename" or die "Couldn't open filename: $!"; process($fh); close $fh or die "Couldn't close filename: $!"; Suppose that process might die. Then the code block exits early, and $fh doesn't get closed. I could explicitly check for errors: open my $fh, "<", "filename" or die "Couldn't open filename: $!"; eval {process($fh)}; my $saved_error = $@; close $fh or die "Couldn't close filename: $!"; die $saved_error if $saved_error; but this kind of code is notoriously difficult to get right, and only gets more complicated when you add more resources. In C++ I would use RAII to create an object which owns the resource, and whose destructor would free it. That way, I don't have to remember to free the resource, and resource cleanup happens correctly as soon as the RAII object goes out of scope - even if an exception is thrown. Unfortunately in Perl a DESTROY method is unsuitable for this purpose as there are no guarantees for when it will be called. Is there a Perlish way to ensure resources are automatically freed like this even in the presence of exceptions? Or is explicit error checking the only option?

    Read the article

  • How can I automatically release resources RAII-style in Perl?

    - by Philip Potter
    Say I have a resource (e.g. a filehandle or network socket) which has to be freed: open my $fh, "<", "filename" or die "Couldn't open filename: $!"; process($fh); close $fh or die "Couldn't close filename: $!"; Suppose that process might die. Then the code block exits early, and $fh doesn't get closed. I could explicitly check for errors: open my $fh, "<", "filename" or die "Couldn't open filename: $!"; eval {process($fh)}; my $saved_error = $@; close $fh or die "Couldn't close filename: $!"; die $saved_error if $saved_error; but this kind of code is notoriously difficult to get right, and only gets more complicated when you add more resources. In C++ I would use RAII to create an object which owns the resource, and whose destructor would free it. That way, I don't have to remember to free the resource, and resource cleanup happens correctly as soon as the RAII object goes out of scope - even if an exception is thrown. Unfortunately in Perl a DESTROY method is unsuitable for this purpose as there are no guarantees for when it will be called. Is there a Perlish way to ensure resources are automatically freed like this even in the presence of exceptions? Or is explicit error checking the only option?

    Read the article

  • curl halts script execution

    - by Funky Dude
    my script uses curl to upload images to smugsmug site via smugsmug api. i loop through a folder and upload every image in there. but after 3-4 uploads, curl_exec would fail, stopped everything and prevent other images from uploading. $upload_array = array( "method" => "smugmug.images.upload", "SessionID" => $session_id, "AlbumID" => $alb_id, "FileName" => zerofill($n, 3) . ".jpg", "Data" => base64_encode($data), "ByteCount" => strlen($data), "MD5Sum" => $data_md5); $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_POSTFIELDS, $upload_array); curl_setopt( $ch, CURLOPT_URL, "https://upload.smugmug.com/services/api/rest/1.2.2/"); $upload_result = curl_exec($ch); //fails here curl_close($ch); updated: so i added logging into my script. when it does fail, the logging stops after fwrite($fh, "begin curl\n"); fwrite($fh, "begin curl\n"); $upload_result = curl_exec($ch); fwrite($fh, "curl executed\n"); fwrite($fh, "curl info: ".print_r(curl_getinfo($ch,true))."\n"); fwrite($fh, "xml dump: $upload_result \n"); fwrite($fh, "curl error: ".curl_error($ch)."\n"); i also curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60*60);

    Read the article

  • download file, without saving in server

    - by lolalola
    Hi, Or possible for users to download the file without saving it on the server? I am getting data from the database, and I want to save them .doc (MS Word) file. if(isset($_POST['save'])) { $file = "new_file2.doc"; $stringData = "Text text text text...."; //This data put in new Word file $fh = fopen($file, 'w'); fwrite($fh, $stringData); fclose($fh); header('Content-Description: File Transfer'); header('Content-type: application/msword'); header('Content-Disposition: attachment; filename="'.$file.'"'); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); unlink($file); exit; } How should the code look like without this: " $fh = fopen($file, 'w'); fwrite($fh, $stringData); fclose($fh);" and this "unlink($file);" I hope to understand what I need enter code here

    Read the article

  • PHP unlink OR rewrite own/current file by itself

    - by Email
    Hi Task: Cut or erase a file after first walk-through. i have an install file called "index.php" which creates another php file. <? /* here some code*/ $fh = fopen($myFile, 'w') or die("can't open file"); $stringData = "<?php \n echo 'hallo, *very very long text*'; \n ?>"; fwrite($fh, $stringData); /*herecut"/ /*here some code */ after the creation of the new file this file is called and i intent to erase the filecreation call since it is very long and only needed on first install. i therefor add to the above code echo 'hallo, *very very long text*'; \n ***$new= file_get_contents('index.php'); \n $findme = 'habanot'; $pos = strpos($new, $findme); if ($pos === false) { $marker='herecut';\n $new=strstr($new,$marker);\n $new='<?php \n /*habanot*/\n'.$new;\n $fh = fopen('index.php', 'w') or die 'cant open file'); $stringData = $new; fwrite($fh, $stringData); fclose($fh);*** ?>"; fwrite($fh, $stringData);]} Isnt there an easier way or a function to modify the current file or even "self destroy" a file after first call? Regards

    Read the article

  • Question about DBD::CSB Statement-Functions

    - by sid_com
    From the SQL::Statement::Functions documentation: Function syntax When using SQL::Statement/SQL::Parser directly to parse SQL, functions (either built-in or user-defined) may occur anywhere in a SQL statement that values, column names, table names, or predicates may occur. When using the modules through a DBD or in any other context in which the SQL is both parsed and executed, functions can occur in the same places except that they can not occur in the column selection clause of a SELECT statement that contains a FROM clause. # valid for both parsing and executing SELECT MyFunc(args); SELECT * FROM MyFunc(args); SELECT * FROM x WHERE MyFuncs(args); SELECT * FROM x WHERE y < MyFuncs(args); # valid only for parsing (won't work from a DBD) SELECT MyFunc(args) FROM x WHERE y; Reading this I would expect that the first SELECT-statement of my example shouldn't work and the second should but it is quite the contrary. #!/usr/bin/env perl use warnings; use strict; use 5.010; use DBI; open my $fh, '>', 'test.csv' or die $!; say $fh "id,name"; say $fh "1,Brown"; say $fh "2,Smith"; say $fh "7,Smith"; say $fh "8,Green"; close $fh; my $dbh = DBI->connect ( 'dbi:CSV:', undef, undef, { RaiseError => 1, f_ext => '.csv', }); my $table = 'test'; say "\nSELECT 1"; my $sth = $dbh->prepare ( "SELECT MAX( id ) FROM $table WHERE name LIKE 'Smith'" ); $sth->execute (); $sth->dump_results(); say "\nSELECT 2"; $sth = $dbh->prepare ( "SELECT * FROM $table WHERE id = MAX( id )" ); $sth->execute (); $sth->dump_results(); outputs: SELECT 1 '7' 1 rows SELECT 2 Unknown function 'MAX' at /usr/lib/perl5/site_perl/5.10.0/SQL/Parser.pm line 2893. DBD::CSV::db prepare failed: Unknown function 'MAX' at /usr/lib/perl5/site_perl/5.10.0/SQL/Parser.pm line 2894. [for Statement "SELECT * FROM test WHERE id = MAX( id )"] at ./so_3.pl line 30. DBD::CSV::db prepare failed: Unknown function 'MAX' at /usr/lib/perl5/site_perl/5.10.0/SQL/Parser.pm line 2894. [for Statement "SELECT * FROM test WHERE id = MAX( id )"] at ./so_3.pl line 30. Could someone explaine me this behavior?

    Read the article

  • TC hashing filters - single rule deletion

    - by exa
    For traffic shaping I'm currently using a setup that looks exactly like the setup from LARTC, on this page: http://lartc.org/howto/lartc.adv-filter.hashing.html I have a simple problem with that - everytime I want to modify something in the hash table (like assign a IP to different flowid), I need to delete the whole filter table and add it again filter by filter. (I actually don't do it by hand, I have a nice program that does it for me... but still...) There is a problem - I got roughly 10k filters allocated this way and deleting and refilling the whole filtertable can get pretty lengthy, which is not exactly good for traffic shaping. My program could easily manage to delete only the rules that need to be deleted (thus reducing the whole problem to several commands and miliseconds), but I simply don't know the command that deletes only the one hashing rule. My tc filter show: filter parent 1: protocol ip pref 1 u32 filter parent 1: protocol ip pref 1 u32 fh 2: ht divisor 256 filter parent 1: protocol ip pref 1 u32 fh 2:a:800 order 2048 key ht 2 bkt a flowid 1:101 match 0a0a0a0a/ffffffff at 16 filter parent 1: protocol ip pref 1 u32 fh 2:c:800 order 2048 key ht 2 bkt c flowid 1:102 match 0a0a0a0c/ffffffff at 16 filter parent 1: protocol ip pref 1 u32 fh 800: ht divisor 1 filter parent 1: protocol ip pref 1 u32 fh 800::800 order 2048 key ht 800 bkt 0 link 2: match 00000000/00000000 at 16 hash mask 000000ff at 16 The wish: 'tc filter del ...' command that removes only one specific filter (for example the 0a0a0a0a IP match (IP address 10.10.10.10)). Removal of some small subgroup would also be good - for example I could still recreate a bucket (bkt a) pretty fast. My attempts: I tried to number all the filters using prio, but with no help -- they just create something unusuable (but deletable) below, but the bucketed filters remain there after that gets deleted. Any ideas? edit - I'm adding a simplified tl;dr description of the problem: I created hash filter on some interfce just like in this http://lartc.org/howto/lartc.adv-filter.hashing.html I want to find a command that deletes one rule (e.g. 1.2.1.123) from the table, leaving the rest untouched and working.

    Read the article

  • Determine how much can I write into a filehandle; copying data from one FH to the other.

    - by Vi
    How to determine if I can write the given number of bytes to a filehandle (socket actually)? (Alternatively, how to "unread" the data I had read from other filehandle?) I want something like: n = how_much_can_I_write(w_handle); n = read(r_handle, buf, n); assert(n==write(w_handle, buf, n)); Both filehandles (r_handle and w_handle) have received ready status from epoll_wait. I want all data from r_handle to be copied to w_handle without using a "write debt" buffer. In general, how to copy the data from one filehandle to the other simply and reliably?

    Read the article

  • Parse SyndicationItem to c# class

    - by user285677
    What's the best way to parse the folowing rss Syndication Item into a c# class: <rss version="2.0" xmlns:fh="http://rss.flightstats.com/ns/rss/1.0"> <channel> <title>FlightStats - Lisboa Airport Departures</title> <language>en-us</language> <copyright>Copyright (c) 2007 Conducive Technology Inc. All rights reserved.</copyright> <description>FlightStats is your source for airport and flight information</description> <link>http://www.flightstats.com?utm_source=49e3481552e7c4c9:4e080df5:1281bf8969d:60e0&utm_medium=cpc&utm_campaign=rss</link> <pubDate>Sun, 25 Apr 2010 12:30:14 +0000</pubDate> <lastBuildDate>Sun, 25 Apr 2010 12:30:14 +0000</lastBuildDate> <ttl>15</ttl> <image> <url>http://dem5xqcn61lj8.cloudfront.net/Widgets/images/flightstats_logo_widget.gif</url> <title>FlightStats - Lisboa Airport Departures</title> <link>http://www.flightstats.com?utm_source=49e3481552e7c4c9:4e080df5:1281bf8969d:60e0&utm_medium=cpc&utm_campaign=rss</link> </image> <item> <fh:FlightHistory FlightHistoryId="190011545" DepartureDate="2010-04-25 12:00" ArrivalDate="2010-04-25 14:45" PublishedDepartureDate="2010-04-25 12:00" PublishedArrivalDate="2010-04-25 14:45" ScheduledGateDepartureDate="2010-04-25 12:00" ScheduledGateArrivalDate="2010-04-25 14:45" EstimatedGateArrivalDate="2010-04-25 14:40" ActualRunwayDepartureDate="2010-04-25 12:13" FlightNumber="8461" StatusCode="A" Status="Active" CreatorCode="O" ScheduledBlockTime="105" DepartureAirportTimeZoneOffset="1" ArrivalAirportTimeZoneOffset="2" ScheduledAircraftType="320" DepartureTerminal="T1" ArrivalTerminal="1" TrackingEnabled="False"> <fh:Airline AirlineCode="VY" Name="Vueling Airlines" /> <fh:Origin AirportCode="LIS" Name="Lisboa Airport" City="Lisbon" CountryCode="PT" /> <fh:Destination AirportCode="BCN" Name="Barcelona Airport" City="Barcelona" StateCode="SP" CountryCode="ES" /> </fh:FlightHistory> <guid isPermaLink="false">VY8461LISBCN</guid> <title>VY 8461 LIS-BCN Departed</title> <description> teste </description> <link>http://www.flightstats.com/go/FlightStatus/flightStatusByFlight.do? id=190011545&utm_source=49e3481552e7c4c9:4e080df5:1281bf8969d:60e0&utm_medium=cpc&utm_campaign=rss</link> </item> </channel> </rss>

    Read the article

  • Draw a Custom cell for tableview ( uitableview ) , with changed colors and separator color and width

    - by Madhup
    Hi, I want to draw the background of a UITableViewCell which has a grouped style. The problem with me is I am not able to call the -(void)drawRect:(CGRect)rect or I think it should be called programmatically... I have taken code from following link . http://stackoverflow.com/questions/400965/how-to-customize-the-background-border-colors-of-a-grouped-table-view/1031593#1031593 // // CustomCellBackgroundView.h // // Created by Mike Akers on 11/21/08. // Copyright 2008 __MyCompanyName__. All rights reserved. // #import <UIKit/UIKit.h> typedef enum { CustomCellBackgroundViewPositionTop, CustomCellBackgroundViewPositionMiddle, CustomCellBackgroundViewPositionBottom, CustomCellBackgroundViewPositionSingle } CustomCellBackgroundViewPosition; @interface CustomCellBackgroundView : UIView { UIColor *borderColor; UIColor *fillColor; CustomCellBackgroundViewPosition position; } @property(nonatomic, retain) UIColor *borderColor, *fillColor; @property(nonatomic) CustomCellBackgroundViewPosition position; @end // // CustomCellBackgroundView.m // // Created by Mike Akers on 11/21/08. // Copyright 2008 __MyCompanyName__. All rights reserved. // #import "CustomCellBackgroundView.h" static void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth,float ovalHeight); @implementation CustomCellBackgroundView @synthesize borderColor, fillColor, position; - (BOOL) isOpaque { return NO; } - (id)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { // Initialization code } return self; } - (void)drawRect:(CGRect)rect { // Drawing code CGContextRef c = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(c, [fillColor CGColor]); CGContextSetStrokeColorWithColor(c, [borderColor CGColor]); CGContextSetLineWidth(c, 2.0); if (position == CustomCellBackgroundViewPositionTop) { CGFloat minx = CGRectGetMinX(rect) , midx = CGRectGetMidX(rect), maxx = CGRectGetMaxX(rect) ; CGFloat miny = CGRectGetMinY(rect) , maxy = CGRectGetMaxY(rect) ; minx = minx + 1; miny = miny + 1; maxx = maxx - 1; maxy = maxy ; CGContextMoveToPoint(c, minx, maxy); CGContextAddArcToPoint(c, minx, miny, midx, miny, ROUND_SIZE); CGContextAddArcToPoint(c, maxx, miny, maxx, maxy, ROUND_SIZE); CGContextAddLineToPoint(c, maxx, maxy); // Close the path CGContextClosePath(c); // Fill & stroke the path CGContextDrawPath(c, kCGPathFillStroke); return; } else if (position == CustomCellBackgroundViewPositionBottom) { CGFloat minx = CGRectGetMinX(rect) , midx = CGRectGetMidX(rect), maxx = CGRectGetMaxX(rect) ; CGFloat miny = CGRectGetMinY(rect) , maxy = CGRectGetMaxY(rect) ; minx = minx + 1; miny = miny ; maxx = maxx - 1; maxy = maxy - 1; CGContextMoveToPoint(c, minx, miny); CGContextAddArcToPoint(c, minx, maxy, midx, maxy, ROUND_SIZE); CGContextAddArcToPoint(c, maxx, maxy, maxx, miny, ROUND_SIZE); CGContextAddLineToPoint(c, maxx, miny); // Close the path CGContextClosePath(c); // Fill & stroke the path CGContextDrawPath(c, kCGPathFillStroke); return; } else if (position == CustomCellBackgroundViewPositionMiddle) { CGFloat minx = CGRectGetMinX(rect) , maxx = CGRectGetMaxX(rect) ; CGFloat miny = CGRectGetMinY(rect) , maxy = CGRectGetMaxY(rect) ; minx = minx + 1; miny = miny ; maxx = maxx - 1; maxy = maxy ; CGContextMoveToPoint(c, minx, miny); CGContextAddLineToPoint(c, maxx, miny); CGContextAddLineToPoint(c, maxx, maxy); CGContextAddLineToPoint(c, minx, maxy); CGContextClosePath(c); // Fill & stroke the path CGContextDrawPath(c, kCGPathFillStroke); return; } else if (position == CustomCellBackgroundViewPositionSingle) { CGFloat minx = CGRectGetMinX(rect) , midx = CGRectGetMidX(rect), maxx = CGRectGetMaxX(rect) ; CGFloat miny = CGRectGetMinY(rect) , midy = CGRectGetMidY(rect) , maxy = CGRectGetMaxY(rect) ; minx = minx + 1; miny = miny + 1; maxx = maxx - 1; maxy = maxy - 1; CGContextMoveToPoint(c, minx, midy); CGContextAddArcToPoint(c, minx, miny, midx, miny, ROUND_SIZE); CGContextAddArcToPoint(c, maxx, miny, maxx, midy, ROUND_SIZE); CGContextAddArcToPoint(c, maxx, maxy, midx, maxy, ROUND_SIZE); CGContextAddArcToPoint(c, minx, maxy, minx, midy, ROUND_SIZE); // Close the path CGContextClosePath(c); // Fill & stroke the path CGContextDrawPath(c, kCGPathFillStroke); return; } } - (void)dealloc { [borderColor release]; [fillColor release]; [super dealloc]; } @end static void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth,float ovalHeight) { float fw, fh; if (ovalWidth == 0 || ovalHeight == 0) {// 1 CGContextAddRect(context, rect); return; } CGContextSaveGState(context);// 2 CGContextTranslateCTM (context, CGRectGetMinX(rect),// 3 CGRectGetMinY(rect)); CGContextScaleCTM (context, ovalWidth, ovalHeight);// 4 fw = CGRectGetWidth (rect) / ovalWidth;// 5 fh = CGRectGetHeight (rect) / ovalHeight;// 6 CGContextMoveToPoint(context, fw, fh/2); // 7 CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);// 8 CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);// 9 CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);// 10 CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1); // 11 CGContextClosePath(context);// 12 CGContextRestoreGState(context);// 13 } but the problem is my drawRect is not getting called automatically......... I am doing it like this. CustomCellBackgroundView *custView = [[CustomCellBackgroundView alloc] initWithFrame:CGRectMake(0,0,320,44)]; [cell setBackgroundView:custView]; [custView release]; and doing this gives me transparent cell. I tried and fought with code but could get any results. Please help me out. I am really having no idea how this code will run.

    Read the article

  • What is the safe way to use fork with Apache::DBI under mod_perl2?

    - by codeholic
    I have a problem when I use Apache::DBI in child processes. The problem is that Apache::DBI provides a single handle for all processes which use it, so I get DBD::mysql::db selectall_arrayref failed: Commands out of sync; you can't run this command now at /usr/local/www/apache22/data/test-fork.cgi line 20. Reconnection doesn't help, since Apache::DBI reconnects in all processes, as I understood the following error The server encountered an internal error and was unable to complete your request. Error message: DBD driver has not implemented the AutoCommit attribute at /usr/local/lib/perl5/site_perl/5.8.9/Apache/DBI.pm line 283. , Here's the origin code: use Data::Dumper 'Dumper'; use DBI (); my $dbh = DBI->connect($dsn, $username, $password, { RaiseError => 1, PrintError => 0, }); my $file = "/tmp/test-fork.tmp"; my $pid = fork; defined $pid or die "fork: $!"; if ($pid) { my $rows = eval { $dbh->selectall_arrayref('SELECT SLEEP(1)') }; print "Content-Type: text/plain\n\n"; print $rows ? "parent: " . Dumper($rows) : $@; } else { my $rows = eval { $dbh->selectall_arrayref('SELECT SLEEP(1)') }; open FH, '>', $file or die "$file: $!"; print FH $rows ? "child: " . Dumper($rows) : $@; close FH; } The code I used for reconnection: ... else { $dbh->disconnect; $dbh = DBI->connect($dsn, $username, $password, $attrs); my $rows = eval { $dbh->selectall_arrayref('SELECT SLEEP(1)') }; open FH, '>', $file or die "$file: $!"; print FH $rows ? "child: " . Dumper($rows) : $@; close FH; } Is there a safe way to use Apache::DBI with forking? Is there a way to make it create a new connection perhaps?

    Read the article

  • Writing to a new line of a file in Objective-C

    - by Kulpreet
    For some strange reason, the \n and \r escape sequences do not seem to be working in my code. I want to write each NSString on a new line of the file, but it just appends it the last string on one line. Here's the code: for (Entry *entry in self.entries) { NSString *path = @"/Users/me/File.txt"; NSString *string = (@"%@\r\n", [entry thisEntry]); NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:path]; [fh seekToEndOfFile]; [fh writeData:[string dataUsingEncoding:NSUnicodeStringEncoding]]; [fh closeFile]; } Am I doing something wrong? Forgive me as I am new to Objective-C.

    Read the article

  • using fopen on uploaded file with php

    - by Patrick
    Im uploading a file, and then attempting to use fgetcsv to do things to it. This is my script below. Everything was working fine before i added the file upload portions. Now its not showing any errors, its just not displaying the uploaded data. Im getting my "file uploaded" notice, and the file is saving properly, but the counter for number of entries is showing 0. if(isset($_FILES[csvgo])){ $tmp = $_FILES[csvgo][tmp_name]; $name = "temp.csv"; $tempdir = "csvtemp/"; if(move_uploaded_file($tmp, $tempdir.$name)){ echo "file uploaded<br>"; } $csvfile = $tempdir.$name; $fh = fopen($csvfile, 'r'); $headers = fgetcsv($fh); $data = array(); while (! feof($fh)) { $row = fgetcsv($fh); if (!empty($row)) { $obj = new stdClass; foreach ($row as $i => $value) { $key = $headers[$i]; $obj->$key = $value; } $data[] = $obj; } } fclose($fh); $c=0; foreach($data AS $key){ $c++; $phone = $key->PHONE; $fax = $key->Fax; $email = $key->Email; // do things with the data here } echo "$c entries <br>"; }

    Read the article

  • php upload image with ftp problem

    - by ntan
    Hi, I am using the code below to upload an image through ftp $sFile=$ftp_dir."/".$image_name; $image=$database_row["image"];//image is store in database $fh = tmpfile(); $fwrite($fh, $image); $uploadFile = ftp_fput($conn_id, $sFile, $fh, FTP_ASCII); fclose($fh); The ftp is creating the file and has a size BUT the file i get is not an image.When try to open on image viewer i get error. Before switch to ftp i had this code $image=$database_row["image"];//image is store in database $file = fopen( "images/".$image_name, "w" ); fwrite( $file, $image); fclose( $file ); and was working fine, but now i have to use ftp. What am i missing.

    Read the article

  • Loading Files in AppEngine

    - by Chris M
    I've got a tiny bit of code to display a file in app.yaml - url: /(.*\.(gif|png|jpg)) static_files: static/\1 upload: static/(.*\.(gif|png|jpg)) in main.py ... class ShowImage(webapp.RequestHandler): def get(self): rootpath = os.path.dirname(__file__) file = rootpath + "/static/tracker.gif"; fh=open(file, 'r') self.response.out.write(fh.read()) fh.close ... I can see the files gone up by going to my *.appspot.com/tracker.gif (as per the app.yaml) But using *.appspot.com/showimage returns Traceback (most recent call last): File "/base/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 510, in __call__ handler.get(*groups) File "/base/data/home/apps/APPNAME/2.341131266814384624/main.py", line 170, in get fh=open(file, 'r') IOError: [Errno 2] No such file or directory: '/base/data/home/apps/APPNAME/2.341131266814384624/static/tracker.gif'

    Read the article

  • how can i disable the default console handler, while using the java logging api ?

    - by loudiyimo
    Hi I am trying to implement the java logging in my application. I want to use two handlers. A file handler and my own console handler. Both of my handlers work fine. My logging is send to a file and to the console . My logging is also sent to the default console handler, which i do not want. If you run my code you will see extra two line sent to the console. I don't want to use de default console handler. Does anyone know how to disable the default console handler. I only want to use the two hadlers i have created. Handler fh = new FileHandler("test.txt"); fh.setFormatter(formatter); logger.addHandler(fh); Handler ch = new ConsoleHandler(); ch.setFormatter(formatter); logger.addHandler(ch); import java.util.Date; import java.util.logging.ConsoleHandler; import java.util.logging.FileHandler; import java.util.logging.Formatter; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.LogRecord; import java.util.logging.Logger; public class LoggingExample { private static Logger logger = Logger.getLogger("test"); static { try { logger.setLevel(Level.INFO); Formatter formatter = new Formatter() { @Override public String format(LogRecord arg0) { StringBuilder b = new StringBuilder(); b.append(new Date()); b.append(" "); b.append(arg0.getSourceClassName()); b.append(" "); b.append(arg0.getSourceMethodName()); b.append(" "); b.append(arg0.getLevel()); b.append(" "); b.append(arg0.getMessage()); b.append(System.getProperty("line.separator")); return b.toString(); } }; Handler fh = new FileHandler("test.txt"); fh.setFormatter(formatter); logger.addHandler(fh); Handler ch = new ConsoleHandler(); ch.setFormatter(formatter); logger.addHandler(ch); LogManager lm = LogManager.getLogManager(); lm.addLogger(logger); } catch (Throwable e) { e.printStackTrace(); } } public static void main(String[] args) { logger.info("why does my test application use the standard console logger ?\n" + " I want only my console handler (Handler ch)\n " + "how can i turn the standard logger to the console off. ??"); } }

    Read the article

  • Ruby: output not saved to file

    - by Sophie
    I'm trying to give a file as input, have it changed within the program, and save the result to a file that is output. But the output file is the same as the input file. :/ Total n00b question, but what am I doing wrong?: puts "Reading Celsius temperature value from data file..." num = File.read("temperature.dat") celsius = num.to_i farenheit = (celsius * 9/5) + 32 puts "Saving result to output file 'faren_temp.out'" fh = File.new("faren_temp.out", "w") fh.puts farenheit fh.close

    Read the article

  • PHP write file... need help

    - by Jordan Pagaduan
    <?php $title = $_POST['title']; $filename = $title , ".php"; $fh = fopen($filename, 'w') or die ("can't open file"); $stringData = $title; fwrite($fh, $stringData); $stringData = $blog; fwrite($fh, $stringData); fclose($fh); ?> This is only a sample. What is the correct code for that?

    Read the article

  • Whhether or not it is an elegant way in such a situation?

    - by z_axis
    There are some text files which needed to be manipulated line by line. I wrote a withFile function as below: let withFile fn handle = let rec iter_lines fh = try handle (input_line fh); iter_lines fh with _ -> close_in fh in iter_lines (open_in fn);; So i can manipulate each file as : withFile "file1.txt" (fun line -> (*...*)) withFile "file2.txt" (fun line -> (*...*)) ... But i amnot sure how to exit elehantly when i donot want to handle all lines. For example: withFile "file3.txt" (fun line -> (*when the line meets some condition, i will exit without handling other lines*) ); Any suggestion is appreciated !

    Read the article

1 2 3 4 5  | Next Page >