Search Results

Search found 151 results on 7 pages for 'unlink'.

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

  • 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

  • PHP Unlink function Woes on Windows

    - by Abs
    Hello all, I am having problems with the PHP function unlink. I keep getting this error: Warning: unlink(C:\wamp\www\webs\db\db_1276259188.mdb) [function.unlink]: Permission denied in C:\wamp\www\webs\pure-php-export.php on line 242 I am on a windows machine where Apache runs as the user SYSTEM. I have set the permissions of the db folder as "Full Control" for Apache's user. I thought my script might still be holding on to that file (its an uploaded file that gets used via PDO). try{ $dbh = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=$mdbFilename", $username, $password); }catch(PDOException $e){ echo $e->getMessage(); } So before I attempt to delete the file I unset the above and try to delete like so: $dbh = null; unset($dbh); if(is_file($mdbFilename)){ unlink($mdbFilename); } I really appreciate any help on this as it has been driving me mental for the past two hours! Thanks all for any help.

    Read the article

  • How do I unlink a file-folder relationship?

    - by Ovesh
    When asking IE to save an HTML page locally, with the option "Web page, complete", an html file is created along with a folder that contains all associated files (images, js, css etc). An association is created between the html file and the folder, so that when the file is deleted/moved, so is the folder. First, I'd like to know what this kind of association is called. Further, I'd like to know how to "unlink" this file-folder association.

    Read the article

  • What does "warning: unable to unlink website: Operation not permitted" mean when checking out a Git

    - by James A. Rosen
    I'm trying to create a local branch that tracks a remote branch. Here's what I get: > git checkout master > git push origin origin:refs/heads/myBranch Total 0 (delta 0), reused 0 (delta 0) To [email protected]:myrepo/myproject.git * [new branch] origin/HEAD -> myBranch > git fetch origin > git checkout --track -b myBranch origin/myBranch warning: unable to unlink website: Operation not permitted Branch myBranch set up to track remote branch myBranch from origin. Switched to a new branch 'myBranch' What does "warning: unable to unlink website: Operation not permitted" mean? Did everything work fine?

    Read the article

  • Problem with unlink() in php!

    - by Holicreature
    I'm creating a temp image always named 1.png under specific folder and once i read the image_contents and process, i use unlink() to delete that specific image from that folder. But sometimes the image file is not deleted and the same image is file is read and processed. That script is working otherwise fine... There is no permission related issues , as the files are deleted sometimes... Will there be any issue when the script is repeatedly called and the image with the name is already present and not deleted etc.. ??? Please suggest me what would be the problem extension_loaded('ffmpeg'); $max_width = 120; $max_height = 72; $path ="/home/fff99/public_html/temp/"; ..... ..... $nname = "/home/friend99/public_html/temp/".$imgname; $fileo = fopen($nname,"rb"); if($fileo) { $imgData = addslashes(file_get_contents($nname)); .... ... .. } unlink('$nname');

    Read the article

  • Delete (not Unlink) a YouTube account?

    - by Kieron
    Hi, How do I go about deleting my YouTube account? It became associated with my Google Account under a stupid name, all I wanted to do was change it to my name. Unfortunatly, it's now become unlinked and I can't do anything with it. Ideally, I'd like to just delete it and start again - I don't think you can rename an account...does anyone know how? Thanks, Kieron

    Read the article

  • (How) does deleting open files on Linux and a FAT file system work?

    - by lxgr
    It's clear to me how deleting open files works on filesystems that use inodes - unlink() just decreases the link count to zero, and when the last file handle to the file is closed, the inode will be removed. But how does it work when using a file system that doesn't use inodes, like FAT32, with Linux? Some experiments suggest that deleting open files is still possible (unlike on Windows, where the unlink call wouldn't succeed), but what happens when the file system is uncleanly unmounted? How does Linux mark the files as unlinked, when the file system itself doesn't support such an operation? Is the directory entry just deleted, but retained in memory (that would guarantee deletion after unmounting in any case, but would leave the file system in an inconsistent state), or will the deletion only be marked in memory, and written at the time the last file handle is closed, avoiding possible corruption, but restoring the deleted files after an unclean unmount?

    Read the article

  • Is it possible for a directory to get unlinked while its contained files remain?

    - by Walkerneo
    I used to wonder why deleting directories via PHP or shell wasn't as easy as it was in Windows with just clicking delete. I realize now that deleting is simply unlinking files from the file allocation table, so to delete a directory, you must unlink all the files inside it. Is it ever possible for the directory's entry to be removed, but not those of the files inside it? Do operating systems periodically check for files that can't be reached in the file system?

    Read the article

  • [Concept] How does unlink() find the file to delete?

    - by Prasad
    My app has a 'Photo' field to store URL. It uses sfWidgetFormInputFileEditable for the widget schema. To delete the old image when a new image is uploaded, I use unlink before setting the value in the over-ridden setter and it works!!! if (file_exists($this->_get('photo'))) unlink($this->_get('photo')); Photos are stored in uploads/photos and when saving 'Photo' only the file name xxx-yyy.zzz is saved (and not the full path). However, I wish to know how symfony/php knows the full path of the file to be deleted? Part 2: I am using sfThumbnailPlugin to generate thumbnails. So the actual code looks like this: public function setPhoto($value) { if(!empty($value)) { Contact::generateThumbnail($value); // delete current Photo & create thumbnail $this->_set('photo',$value); // setting new value after deleting old one } } public function generateThumbnail($value) { $uploadDir = sfConfig::get('app_photo_upload'); // path to upload folder if (file_exists($this->_get('photo'))) { unlink($this->_get('photo')); // delete full-size image // path to thumbnail $thumbpath = $uploadDir.'/thumbnails/'.$this->get('photo'); // read a blog, tried setting dir manually, doesn't work :( //chdir('/thumbnails/'); // tried closing the file too, doesn't work! :( //fclose($thumbpath) or die("can't close file"); //unlink($this->_get('photo')); // doesn't work; no error :( unlink($thumbpath); // doesn't work, no error :( } $thumbnail = new sfThumbnail(150, 150); $thumbnail->loadFile($uploadDir.'/'.$value); $thumbnail->save($uploadDir.'/thumbnails/'.$value, 'image/png'); } Why can't the thumbnail be deleted using unlink()? is the sequence of ops incorrect? Is it because the old thumbnail is displayed in the sfWidgetFormInputFileEditable widget? I've spent hours trying to figure this out, but unable to nail down the real cause. Thanks in advance.

    Read the article

  • code doesnot delete specific extra files but deletes all, also no recursion for directory, help me t

    - by OM The Eternity
    I have to compare two folder structure and with reference of source folder I want to delete all the files/folders present in other destination folder which do not exist in reference source folder, how could i do this? $original = scan_dir_recursive('/var/www/html/copy2'); $mirror = scan_dir_recursive('/var/www/html/copy1'); function scan_dir_recursive($dir) { $all_paths = array(); $new_paths = scandir($dir); foreach ($new_paths as $path) { if ($path == '.' || $path == '..') { continue; } $path = $dir . DIRECTORY_SEPARATOR . $path; if (is_dir($path)) { $all_paths = array_merge($all_paths, scan_dir_recursive($path)); } else { $all_paths[] = $path; } } return $all_paths; } foreach($mirror as $mirr) { if($mirr != '.' && $mirr != '..') { if(!in_array($mirr, $original)) { unlink($mirr); // delete the file } } } The above code shows what i did.. Here My copy1 folder contains extra files than copy2 folders hence i need these extra files to be deleted. Below given output is are arrays of original Mirror and of difference of both.. Original Array ( [0] => /var/www/html/copy2/Copy (5) of New Text Document.txt [1] => /var/www/html/copy2/Copy of New Text Document.txt ) Mirror Array ( [0] => /var/www/html/copy1/Copy (2) of New Text Document.txt [1] => /var/www/html/copy1/Copy (3) of New Text Document.txt [2] => /var/www/html/copy1/Copy (5) of New Text Document.txt ) Difference Array ( [0] => /var/www/html/copy1/Copy (2) of New Text Document.txt [1] => /var/www/html/copy1/Copy (3) of New Text Document.txt [2] => /var/www/html/copy1/Copy (5) of New Text Document.txt ) when i iterate a loop to delete on difference array all files has to be deleted as per displayed output.. how can i rectify this.. the loop for deletion is given below. $dirs_to_delete = array(); foreach ($diff_path as $path) { if (is_dir($path)) { $dirs_to_delete[] = $path; } else { unlink($path); } } while ($dir = array_pop($dirs_to_delete)) { rmdir($dir); }

    Read the article

  • How to make `rm` faster on ext3/linux?

    - by depesz
    I have ext3 filesystem mounted with default options. On it I have some ~ 100GB files. Removal of any of such files takes long time (8 minutes) and causes a lot of io traffic, which increases load on server. Is there any way to make the rm not as disruptive?

    Read the article

  • PHP: deleting files – permission denied – chmod?

    - by mathiregister
    hi guys, i want to delete files from a directory via php. Somehow my php_errorlog always tells me: [06-Jun-2010 19:38:46] PHP Warning: chmod() [function.chmod]: Operation not permitted in /Users/myname/htdocs/ if ($_POST) { echo "yeah!!!"; print count($_POST['deletefiles']); chmod($path, 0777); //server rights foreach ($_POST['deletefiles'] as $value) { print $value; unlink($path .'/' . $value); } //chmod($path, 0666); //server rights } what am I doing wrong? Thank you

    Read the article

  • Unlink deleting more than just the files passed to it.

    - by RMcLeod
    I'm creating an SQL file, placing this file into a zip file with some images and then deleting the SQL file with unlink.Strange thing is it deletes the zip file as well. if (file_put_contents($sqlFileName, $sql) !== false) { $zip = new ZipArchive; if ($zip->open($workingDir . $now . '.zip', ZipArchive::CREATE) === true) { $zip->addFile($sqlFileName, basename($sqlFileName)); if(! empty($images)) { foreach ($images as $image) { $zip->addFile($imagesDir . $image, $image); } } } unlink($sqlFileName); }

    Read the article

  • How does Linux's unlink on a NTFS filesystem differs from Window's own implementation?

    - by DavideRossi
    I have an external USB disk with an NTFS filesystem on it. If I remove a file from Windows and I run one of the several "undelete" utilities (say, TestDisk) I can easily recover the file (because "it's still there but it's marked as deleted"). If I remove the file from Linux (I'm using Ubuntu) no utility can recover the file (unless I use a deep-search signature-based one). Why? It looks like Linux does not just "mark it as deleted" but it wipes away some on-disk structure, is this the case?

    Read the article

  • Editing files without race conditions?

    - by user2569445
    I have a CSV file that needs to be edited by multiple processes at the same time. My question is, how can I do this without introducing race conditions? It's easy to write to the end of the file without race conditions by open(2)ing it in "a" (O_APPEND) mode and simply write to it. Things get more difficult when removing lines from the file. The easiest solution is to read the file into memory, make changes to it, and overwrite it back to the file. If another process writes to it after it is in memory, however, that new data will be lost upon overwriting. To further complicate matters, my platform does not support POSIX record locks, checking for file existence is a race condition waiting to happen, rename(2) replaces the destination file if it exists instead of failing, and editing files in-place leaves empty bytes in it unless the remaining bytes are shifted towards the beginning of the file. My idea for removing a line is this (in pseudocode): filename = "/home/user/somefile"; file = open(filename, "r"); tmp = open(filename+".tmp", "ax") || die("could not create tmp file"); //"a" is O_APPEND, "x" is O_EXCL|O_CREAT while(write(tmp, read(file)); //copy the $file to $file+".new" close(file); //edit tmp file unlink(filename) || die("could not unlink file"); file = open(filename, "wx") || die("another process must have written to the file after we copied it."); //"w" is overwrite, "x" is force file creation while(write(file, read(tmp))); //copy ".tmp" back to the original file unlink(filename+".tmp") || die("could not unlink tmp file"); Or would I be better off with a simple lock file? Appender process: lock = open(filename+".lock", "wx") || die("could not lock file"); file = open(filename, "a"); write(file, "stuff"); close(file); close(lock); unlink(filename+".lock"); Editor process: lock = open(filename+".lock", "wx") || die("could not lock file"); file = open(filename, "rw"); while(contents += read(file)); //edit "contents" write(file, contents); close(file); close(lock); unlink(filename+".lock"); Both of these rely on an additional file that will be left over if a process terminates before unlinking it, causing other processes to refuse to write to the original file. In my opinion, these problems are brought on by the fact that the OS allows multiple writable file descriptors to be opened on the same file at the same time, instead of failing if a writable file descriptor is already open. It seems that O_CREAT|O_EXCL is the closest thing to a real solution for preventing filesystem race conditions, aside from POSIX record locks. Another possible solution is to separate the file into multiple files and directories, so that more granular control can be gained over components (lines, fields) of the file using O_CREAT|O_EXCL. For example, "file/$id/$field" would contain the value of column $field of the line $id. It wouldn't be a CSV file anymore, but it might just work. Yes, I know I should be using a database for this as databases are built to handle these types of problems, but the program is relatively simple and I was hoping to avoid the overhead. So, would any of these patterns work? Is there a better way? Any insight into these kinds of problems would be appreciated.

    Read the article

  • Paypal development. encrypt transactions. php p12

    - by ninchen
    when i take a look at the paypal documentation, they say "Note that the PayPal SDK for PHP does not require SSL encryption". https://developer.paypal.com/docs/classic/api/apiCredentials/#encrypting-your-certificate Is the statement of this phrase, that i don't have to create a p12 certificate when working with php, but use the public_key.pem and paypal_public_key.pem? If yes: Is it secure enough to create the encrypted form input elements without p12 certificate? If no: What do they mean? :-) Before this question came up, i've tested this little programm. http://www.softarea51.com/blog/how-to-integrate-your-custom-shopping-cart-with-paypal-website-payments-standard-using-php/ There is a config file paypal-wps-config.inc.php where i can define the paths to my certificates. // tryed to use // 'paypal_cert.p12 '; $config['private_key_path'] = '/home/folder/.cert/pp/prvkey.pem'; // must match the one you set when you created the private key $config['private_key_password'] = ''; //'my_password'; When i try to use the p12 certificate, openssl_error_string() returns "Could not sign data: error:0906D06C:PEM routines:PEM_read_bio:no start line openssl_pkcs7_sign When i instead use the prvkey.pem without password all works fine. Here is the function, which signs and encrypt the data. function signAndEncrypt($dataStr_, $ewpCertPath_, $ewpPrivateKeyPath_, $ewpPrivateKeyPwd_, $paypalCertPath_) { $dataStrFile = realpath(tempnam('/tmp', 'pp_')); $fd = fopen($dataStrFile, 'w'); if(!$fd) { $error = "Could not open temporary file $dataStrFile."; return array("status" => false, "error_msg" => $error, "error_no" => 0); } fwrite($fd, $dataStr_); fclose($fd); $signedDataFile = realpath(tempnam('/tmp', 'pp_')); **// here the error came from** if(!@openssl_pkcs7_sign( $dataStrFile, $signedDataFile, "file://$ewpCertPath_", array("file://$ewpPrivateKeyPath_", $ewpPrivateKeyPwd_), array(), PKCS7_BINARY)) { unlink($dataStrFile); unlink($signedDataFile); $error = "Could not sign data: ".openssl_error_string(); return array("status" => false, "error_msg" => $error, "error_no" => 0); } unlink($dataStrFile); $signedData = file_get_contents($signedDataFile); $signedDataArray = explode("\n\n", $signedData); $signedData = $signedDataArray[1]; $signedData = base64_decode($signedData); unlink($signedDataFile); $decodedSignedDataFile = realpath(tempnam('/tmp', 'pp_')); $fd = fopen($decodedSignedDataFile, 'w'); if(!$fd) { $error = "Could not open temporary file $decodedSignedDataFile."; return array("status" => false, "error_msg" => $error, "error_no" => 0); } fwrite($fd, $signedData); fclose($fd); $encryptedDataFile = realpath(tempnam('/tmp', 'pp_')); if(!@openssl_pkcs7_encrypt( $decodedSignedDataFile, $encryptedDataFile, file_get_contents($paypalCertPath_), array(), PKCS7_BINARY)) { unlink($decodedSignedDataFile); unlink($encryptedDataFile); $error = "Could not encrypt data: ".openssl_error_string(); return array("status" => false, "error_msg" => $error, "error_no" => 0); } unlink($decodedSignedDataFile); $encryptedData = file_get_contents($encryptedDataFile); if(!$encryptedData) { $error = "Encryption and signature of data failed."; return array("status" => false, "error_msg" => $error, "error_no" => 0); } unlink($encryptedDataFile); $encryptedDataArray = explode("\n\n", $encryptedData); $encryptedData = trim(str_replace("\n", '', $encryptedDataArray[1])); return array("status" => true, "encryptedData" => $encryptedData); } // signAndEncrypt } // PPCrypto The main questions: 1. Is it possible to use p12 cert with php, or is it secure enough to work without it? 2. Why i become an error when using openssl_pkcs7_sign Please help. Greetings ninchen

    Read the article

  • can someone help me fix my code?

    - by user267490
    Hi, I have this code I been working on but I'm having a hard time for it to work. I did one but it only works in php 5.3 and I realized my host only supports php 5.0! do I was trying to see if I could get it to work on my sever correctly, I'm just lost and tired lol <?php //Temporarily turn on error reporting @ini_set('display_errors', 1); error_reporting(E_ALL); // Set default timezone (New PHP versions complain without this!) date_default_timezone_set("GMT"); // Common set_time_limit(0); require_once('dbc.php'); require_once('sessions.php'); page_protect(); // Image settings define('IMG_FIELD_NAME', 'cons_image'); // Max upload size in bytes (for form) define ('MAX_SIZE_IN_BYTES', '512000'); // Width and height for the thumbnail define ('THUMB_WIDTH', '150'); define ('THUMB_HEIGHT', '150'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>whatever</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <style type="text\css"> .validationerrorText { color:red; font-size:85%; font-weight:bold; } </style> </head> <body> <h1>Change image</h1> <?php $errors = array(); // Process form if (isset($_POST['submit'])) { // Get filename $filename = stripslashes($_FILES['cons_image']['name']); // Validation of image file upload $allowedFileTypes = array('image/gif', 'image/jpg', 'image/jpeg', 'image/png'); if ($_FILES[IMG_FIELD_NAME]['error'] == UPLOAD_ERR_NO_FILE) { $errors['img_empty'] = true; } elseif (($_FILES[IMG_FIELD_NAME]['type'] != '') && (!in_array($_FILES[IMG_FIELD_NAME]['type'], $allowedFileTypes))) { $errors['img_type'] = true; } elseif (($_FILES[IMG_FIELD_NAME]['error'] == UPLOAD_ERR_INI_SIZE) || ($_FILES[IMG_FIELD_NAME]['error'] == UPLOAD_ERR_FORM_SIZE) || ($_FILES[IMG_FIELD_NAME]['size'] > MAX_SIZE_IN_BYTES)) { $errors['img_size'] = true; } elseif ($_FILES[IMG_FIELD_NAME]['error'] != UPLOAD_ERR_OK) { $errors['img_error'] = true; } elseif (strlen($_FILES[IMG_FIELD_NAME]['name']) > 200) { $errors['img_nametoolong'] = true; } elseif ( (file_exists("\\uploads\\{$username}\\images\\banner\\{$filename}")) || (file_exists("\\uploads\\{$username}\\images\\banner\\thumbs\\{$filename}")) ) { $errors['img_fileexists'] = true; } if (! empty($errors)) { unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file } // Create thumbnail if (empty($errors)) { // Make directory if it doesn't exist if (!is_dir("\\uploads\\{$username}\\images\\banner\\thumbs\\")) { // Take directory and break it down into folders $dir = "uploads\\{$username}\\images\\banner\\thumbs"; $folders = explode("\\", $dir); // Create directory, adding folders as necessary as we go (ignore mkdir() errors, we'll check existance of full dir in a sec) $dirTmp = ''; foreach ($folders as $fldr) { if ($dirTmp != '') { $dirTmp .= "\\"; } $dirTmp .= $fldr; mkdir("\\".$dirTmp); //ignoring errors deliberately! } // Check again whether it exists if (!is_dir("\\uploads\\$username\\images\\banner\\thumbs\\")) { $errors['move_source'] = true; unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file } } if (empty($errors)) { // Move uploaded file to final destination if (! move_uploaded_file($_FILES[IMG_FIELD_NAME]['tmp_name'], "/uploads/$username/images/banner/$filename")) { $errors['move_source'] = true; unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file } else { // Create thumbnail in new dir if (! make_thumb("/uploads/$username/images/banner/$filename", "/uploads/$username/images/banner/thumbs/$filename")) { $errors['thumb'] = true; unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file } } } } // Record in database if (empty($errors)) { // Find existing record and delete existing images $sql = "SELECT `bannerORIGINAL`, `bannerTHUMB` FROM `agent_settings` WHERE (`agent_id`={$user_id}) LIMIT 1"; $result = mysql_query($sql); if (!$result) { unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file die("<div><b>Error: Problem occurred with Database Query!</b><br /><br /><b>File:</b> " . __FILE__ . "<br /><b>Line:</b> " . __LINE__ . "<br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "</div>"); } $numResults = mysql_num_rows($result); if ($numResults == 1) { $row = mysql_fetch_assoc($result); // Delete old files unlink("/uploads/$username/images/banner/" . $row['bannerORIGINAL']); //delete OLD source file unlink("/uploads/$username/images/banner/thumbs/" . $row['bannerTHUMB']); //delete OLD thumbnail file } // Update/create record with new images if ($numResults == 1) { $sql = "INSERT INTO `agent_settings` (`agent_id`, `bannerORIGINAL`, `bannerTHUMB`) VALUES ({$user_id}, '/uploads/$username/images/banner/$filename', '/uploads/$username/images/banner/thumbs/$filename')"; } else { $sql = "UPDATE `agent_settings` SET `bannerORIGINAL`='/uploads/$username/images/banner/$filename', `bannerTHUMB`='/uploads/$username/images/banner/thumbs/$filename' WHERE (`agent_id`={$user_id})"; } $result = mysql_query($sql); if (!$result) { unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file die("<div><b>Error: Problem occurred with Database Query!</b><br /><br /><b>File:</b> " . __FILE__ . "<br /><b>Line:</b> " . __LINE__ . "<br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "</div>"); } } // Print success message and how the thumbnail image created if (empty($errors)) { echo "<p>Thumbnail created Successfully!</p>\n"; echo "<img src=\"/uploads/$username/images/banner/thumbs/$filename\" alt=\"New image thumbnail\" />\n"; echo "<br />\n"; } } if (isset($errors['move_source'])) { echo "\t\t<div>Error: Failure occurred moving uploaded source image!</div>\n"; } if (isset($errors['thumb'])) { echo "\t\t<div>Error: Failure occurred creating thumbnail!</div>\n"; } ?> <form action="" enctype="multipart/form-data" method="post"> <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_SIZE_IN_BYTES; ?>" /> <label for="<?php echo IMG_FIELD_NAME; ?>">Image:</label> <input type="file" name="<?php echo IMG_FIELD_NAME; ?>" id="<?php echo IMG_FIELD_NAME; ?>" /> <?php if (isset($errors['img_empty'])) { echo "\t\t<div class=\"validationerrorText\">Required!</div>\n"; } if (isset($errors['img_type'])) { echo "\t\t<div class=\"validationerrorText\">File type not allowed! GIF/JPEG/PNG only!</div>\n"; } if (isset($errors['img_size'])) { echo "\t\t<div class=\"validationerrorText\">File size too large! Maximum size should be " . MAX_SIZE_IN_BYTES . "bytes!</div>\n"; } if (isset($errors['img_error'])) { echo "\t\t<div class=\"validationerrorText\">File upload error occured! Error code: {$_FILES[IMG_FIELD_NAME]['error']}</div>\n"; } if (isset($errors['img_nametoolong'])) { echo "\t\t<div class=\"validationerrorText\">Filename too long! 200 Chars max!</div>\n"; } if (isset($errors['img_fileexists'])) { echo "\t\t<div class=\"validationerrorText\">An image file already exists with that name!</div>\n"; } ?> <br /><input type="submit" name="submit" id="image1" value="Upload image" /> </form> </body> </html> <?php ################################# # # F U N C T I O N S # ################################# /* * Function: make_thumb * * Creates the thumbnail image from the uploaded image * the resize will be done considering the width and * height defined, but without deforming the image * * @param $sourceFile Path anf filename of source image * @param $destFile Path and filename to save thumbnail as * @param $new_w the new width to use * @param $new_h the new height to use */ function make_thumb($sourceFile, $destFile, $new_w=false, $new_h=false) { if ($new_w === false) { $new_w = THUMB_WIDTH; } if ($new_h === false) { $new_h = THUMB_HEIGHT; } // Get image extension $ext = strtolower(getExtension($sourceFile)); // Copy source switch($ext) { case 'jpg': case 'jpeg': $src_img = imagecreatefromjpeg($sourceFile); break; case 'png': $src_img = imagecreatefrompng($sourceFile); break; case 'gif': $src_img = imagecreatefromgif($sourceFile); break; default: return false; } if (!$src_img) { return false; } // Get dimmensions of the source image $old_x = imageSX($src_img); $old_y = imageSY($src_img); // Calculate the new dimmensions for the thumbnail image // 1. calculate the ratio by dividing the old dimmensions with the new ones // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable // and the height will be calculated so the image ratio will not change // 3. otherwise we will use the height ratio for the image // as a result, only one of the dimmensions will be from the fixed ones $ratio1 = $old_x / $new_w; $ratio2 = $old_y / $new_h; if ($ratio1 > $ratio2) { $thumb_w = $new_w; $thumb_h = $old_y / $ratio1; } else { $thumb_h = $new_h; $thumb_w = $old_x / $ratio2; } // Create a new image with the new dimmensions $dst_img = ImageCreateTrueColor($thumb_w, $thumb_h); // Resize the big image to the new created one imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y); // Output the created image to the file. Now we will have the thumbnail into the file named by $filename switch($ext) { case 'jpg': case 'jpeg': $result = imagepng($dst_img, $destFile); break; case 'png': $result = imagegif($dst_img, $destFile); break; case 'gif': $result = imagejpeg($dst_img, $destFile); break; default: //should never occur! } if (!$result) { return false; } // Destroy source and destination images imagedestroy($dst_img); imagedestroy($src_img); return true; } /* * Function: getExtension * * Returns the file extension from a given filename/path * * @param $str the filename to get the extension from */ function getExtension($str) { return pathinfo($str, PATHINFO_EXTENSION); } ?>

    Read the article

  • What are the pitfalls of hardlinked files on my desktop PC?

    - by MountainX
    All the identical-content files on my PC are now hardlinked. (My data is completely de-duplicated. It is a consequence of the way I copied my data from my old computer.) What pitfalls do I need to be aware of now that certain actions on one file could silently affect a number of other files? I know that deleting the file I'm working on is not a problem (assuming I deleted it on purpose). It doesn't affect any of the other hardlinked files and I don't see that the delete action would lead to unexpected side effects. Moving or renaming the file is not a problem. I don't see any unexpected consequences. I don't think copying hardlinked files is a problem, but I'm not as confident about any unexpected consequences in this regard. What I have seen is that making a copy (to the same disk) of a hardlinked file with cp keeps the copy hardlinked (i.e., inode number doesn't change in the copy). Copying to another filesystem obviously breaks the hardlink. (I guess one pitfall is forgetting this fact, given that my PC has 3 hard disks.) Changing permissions does affect all linked files. So far this has proven handy. (I made a large number of the hardlinked files read-only.) None of the operations above seem to produce any major unexpected consequences. However, as was pointed out to me by Daniel Beck in a comment, editing or modifying a file can sometimes be a problem. It depends on the tool and maybe the type of edit. (For example, editing small text files using sed seems to always break the link while using nano doesn't.) This introduces the chance that editing one file could affect all the hardlinked files (i.e., alter the original inode). My proposed solution to this is to make all hardlinked files read-only (and that is already mostly the case). If I can't do that for some files, I will unlink those particular files. Is there any problem with this read-only approach? I'm assuming that if I go to edit a file and find it to be read-only, I'll remember to unlink that filename while making it writable. So one pitfall might be forgetting this rule. In that case, I'll have to rely on my backups. Am I correct in the above statements? And what else do I need to know? BTW, I'm running Kubuntu 12.04. I'm also using btrfs. (I have 2 SSD's and 1 HDD in the PC. I will also be adding an external USB HDD. I'm also connected to a network and I mount some NFS shares. I don't assume any of these last bits are relevant to the question, but I'm adding them just in case.) BTW, since I have more than one drive (with separate file systems), to unlink any file all I have to do is copy it to another drive, then move it back. However, using sed also works (in my testing). Here's my script: sed -i 's/\(.\)/\1/' file1 Surprisingly, this even unlinks zero byte files. In my testing it also appears to work on non-text files without any special options. (But I understand that the --binary option might be needed on Windows, MS-DOS and Cygwin.) However, copying to another disk and moving back may be the best way to unlink. For my use-case, unlink command doesn't really "unlink", rather it "removes".

    Read the article

  • Unable to list contents/remove directory (linux ext3)

    - by RedKrieg
    System is CentOS5 x86_64, completely up to date. I've got a folder that can't be listed (ls just hangs, eating memory until it is killed). The directory size is nearly 500k: root@server [/home/user/public_html/domain.com/wp-content/uploads/2010/03]# stat . File: `.' Size: 458752 Blocks: 904 IO Block: 4096 directory Device: 812h/2066d Inode: 44499071 Links: 2 Access: (0755/drwxr-xr-x) Uid: ( 3292/ user) Gid: ( 3287/ user) Access: 2012-06-29 17:31:47.000000000 -0400 Modify: 2012-10-23 14:41:58.000000000 -0400 Change: 2012-10-23 14:41:58.000000000 -0400 I can see the file names if I use ls -1f, but it just repeats the same 48 files ad infinitum, all of which have non-ascii characters somewhere in the file name: La-critic\363-al-servicio-la-privacidad-300x160.jpg When I try to access the files (say to copy them or remove them) I get messages like the following: lstat("/home/user/public_html/domain.com/wp-content/uploads/2010/03/Sebast\355an-Pi\361era-el-balc\363n-150x120.jpg", 0x7fff364c52c0) = -1 ENOENT (No such file or directory) I tried altering the code found on this man page and modified the code to call unlink for each file. I get the same ENOENT error from the unlink call: unlink("/home/user/public_html/domain.com/wp-content/uploads/2010/03/Marca-naci\363n-Madrid-150x120.jpg") = -1 ENOENT (No such file or directory) I also straced a "touch", grabbed the syscalls it makes and replicated them, then tried to unlink the resulting file by name. This works fine, but the folder still contains an entry by the same name after the operation completes and the program runs for an arbitrarily long time (strace output ended up at 20GB after 5 minutes and I stopped the process). I'm stumped on this one, I'd really prefer not to have to take this production machine (hundreds of customers) offline to fsck the filesystem, but I'm leaning toward that being the only option at this point. If anyone's had success using other methods for removing files (by inode number, I can get those with the getdents code) I'd love to hear them. (Yes, I've tried find . -inum <inode> -exec rm -fv {} \; and it still has the problem with unlink returning ENOENT) For those interested, here's the diff between that man page's code and mine. I didn't bother with error checking on mallocs, etc because I'm lazy and this is a one-off: root@server [~]# diff -u listdir-orig.c listdir.c --- listdir-orig.c 2012-10-23 15:10:02.000000000 -0400 +++ listdir.c 2012-10-23 14:59:47.000000000 -0400 @@ -6,6 +6,7 @@ #include <stdlib.h> #include <sys/stat.h> #include <sys/syscall.h> +#include <string.h> #define handle_error(msg) \ do { perror(msg); exit(EXIT_FAILURE); } while (0) @@ -17,7 +18,7 @@ char d_name[]; }; -#define BUF_SIZE 1024 +#define BUF_SIZE 1024*1024*5 int main(int argc, char *argv[]) { @@ -26,11 +27,16 @@ struct linux_dirent *d; int bpos; char d_type; + int deleted; + int file_descriptor; fd = open(argc > 1 ? argv[1] : ".", O_RDONLY | O_DIRECTORY); if (fd == -1) handle_error("open"); + char* full_path; + char* fd_path; + for ( ; ; ) { nread = syscall(SYS_getdents, fd, buf, BUF_SIZE); if (nread == -1) @@ -55,7 +61,24 @@ printf("%4d %10lld %s\n", d->d_reclen, (long long) d->d_off, (char *) d->d_name); bpos += d->d_reclen; + if ( d_type == DT_REG ) + { + full_path = malloc(strlen((char *) d->d_name) + strlen(argv[1]) + 2); //One for the /, one for the \0 + strcpy(full_path, argv[1]); + strcat(full_path, (char *) d->d_name); + + //We're going to try to "touch" the file. + //file_descriptor = open(full_path, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK, 0666); + //fd_path = malloc(32); //Lazy, only really needs 16 + //sprintf(fd_path, "/proc/self/fd/%d", file_descriptor); + //utimes(fd_path, NULL); + //close(file_descriptor); + deleted = unlink(full_path); + if ( deleted == -1 ) printf("Error unlinking file\n"); + break; //Break on first try + } } + break; //Break on first try } exit(EXIT_SUCCESS);

    Read the article

  • Create File Speedily From Individual Column

    - by neversaint
    I have a data that looks like this: -1 1:-0.394668 2:-0.794872 3:-1 4:-0.871341 5:0.9365 6:0.75597 1 1:-0.463641 2:-0.897436 3:-1 4:-0.871341 5:0.44378 6:0.121824 1 1:-0.469432 2:-0.897436 3:-1 4:-0.871341 5:0.32668 6:0.302529 -1 1:-0.241547 2:-0.538462 3:-1 4:-0.871341 5:0.9994 6:0.987166 1 1:-0.757233 2:-0.948718 3:-1 4:-0.871341 5:-0.33904 6:0.915401 1 1:-0.167147 2:-0.589744 3:-1 4:-0.871341 5:0.95078 6:0.991566 The first column is class, and next 6 columns are features. I want to create 6 files for individual features. For example feat1_file.txt will contain -1 1:-0.394668 1 1:-0.463641 ... 1 1:-0.757233 1 1:-0.167147 feat2_file.txt will contain -1 2:-0.794872 ... 1 2:-0.589744 and so on. I have a Perl code that does this but it is horribly slow. Is there a way to do it faster? Typically the input files will contain 100K lines. use strict; use Data::Dumper; use Carp; my $input = $ARGV[0] || "myinput.txt"; my $INFILE_file_name = $input; # input file name open ( INFILE, '<', $INFILE_file_name ) or croak "$0 : failed to open input file $INFILE_file_name : $!\n"; my $out1 = $input."_feat_1.txt"; my $out2 = $input."_feat_2.txt"; my $out3 = $input."_feat_3.txt"; my $out4 = $input."_feat_4.txt"; my $out5 = $input."_feat_5.txt"; my $out6 = $input."_feat_6.txt"; unlink($out1); unlink($out2); unlink($out3); unlink($out4); unlink($out5); unlink($out6); print "$out1\n"; while ( <INFILE> ) { chomp; my @els = split(/\s+/,$_); my $lbl = $els[0]; my $OUTFILE1_file_name = $out1; # output file name open ( OUTFILE1, '>>', $OUTFILE1_file_name ) or croak "$0 : failed to open output file $OUTFILE1_file_name : $!\n"; print OUTFILE1 "$lbl $els[1]\n"; close ( OUTFILE1 ); # close output file my $OUTFILE2_file_name = $out2; # output file name open ( OUTFILE2, '>>', $OUTFILE2_file_name ) or croak "$0 : failed to open output file $OUTFILE2_file_name : $!\n"; print OUTFILE2 "$lbl $els[2]\n"; close ( OUTFILE2 ); # close output file # Etc.. until OUTFILE 6 } close (INFILE);

    Read the article

  • How to remove .zip file in c on windows? (error: Directory not empty)

    - by ExtremeBlue
    include include include include "win32-dirent.h" include include include define MAXFILEPATH 1024 bool IsDirectory(char* path) { WIN32_FIND_DATA w32fd; HANDLE hFindFile; hFindFile = FindFirstFile((PTCHAR)path, &w32fd); if(hFindFile == INVALID_HANDLE_VALUE) { return false; } return w32fd.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY); } int RD(const char* folderName) { DIR *dir; struct dirent *ent; dir = opendir(folderName); if(dir != NULL) { while((ent = readdir(dir)) != NULL) { if(strcmp(ent->d_name , ".") == 0 || strcmp(ent->d_name, "..") == 0) { continue; } char fileName[MAXFILEPATH]; sprintf(fileName,"%s%c%s", folderName, '\\', ent->d_name); if(IsDirectory(fileName)) { RD(fileName); } else { unlink(fileName); } } closedir(dir); //chmod(folderName, S_IWRITE | S_IREAD); if(_rmdir(folderName) != 0)perror(folderName); } else { printf("%s <%s>\n","Could Not Open Directory.", folderName); return -1; } return 0; } int main(int argc, char* argv[]) { if(argc < 2) { printf("usage: ./a.out \n"); return 1; } //RD(argv[1]); //_mkdir("12"); //_mkdir("12\\34"); //_rmdir("12\\34"); //_rmdir("12"); char buf[0xff]; sprintf(buf, "unzip -x -q -d 1234 1234.zip"); system(buf); RD("1234"); //unlink("D:\\dev\\c\\project\\removeFolder\\Debug\\1234\\56\\5.txt"); //unlink("D:\\dev\\c\\project\\removeFolder\\Debug\\1234\\56\\6.txt"); //unlink("D:\\dev\\c\\project\\removeFolder\\Debug\\1234\\1_23.zip"); //unlink("D:\\dev\\c\\project\\removeFolder\\Debug\\1234\\4.txt"); //_rmdir("D:\\dev\\c\\project\\removeFolder\\Debug\\1234\\56"); //_rmdir("D:\\dev\\c\\project\\removeFolder\\Debug\\1234"); return 0; } Archive: 1234.zip inflating: 1234/4.txt inflating: 1234/56/5.txt inflating: 1234/56/6.txt inflating: 1234/1_23.zip

    Read the article

  • Node.js Creating and Deleting a File Recursively

    - by Matt
    I thought it would be a cool experiment to have a for loop and create a file hello.txt and then delete it with unlink. I figured that if fs.unlink is the delete file procedure in Node, then fs.link must be the create file. However, my code will only delete, and it will not create, not even once. Even if I separate the fs.link code into a separate file, it still will not create my file hello.txt. Below is my code: var fs = require('fs'), for(var i=1;i<=10;i++){ fs.unlink('./hello.txt', function (err) { if (err){ throw err; } else { console.log('successfully deleted file'); } fs.link('./hello.txt', function (err) { if (err){ throw err; } else { console.log('successfully created file'); } }); }); } http://nodejs.org/api/fs.html#fs_fs_link_srcpath_dstpath_callback Thank you!

    Read the article

  • Help debugging c fifos code - stack smashing detected - open call not functioning - removing pipes

    - by nunos
    I have three bugs/questions regarding the source code pasted below: stack smashing deteced: In order to compile and not have that error I have addedd the gcc compile flag -fno-stack-protector. However, this should be just a temporary solution, since I would like to find where the cause for this is and correct it. However, I haven't been able to do so. Any clues? For some reason, the last open function call doesn't work and the programs just stops there, without an error, even though the fifo already exists. I want to delete the pipes from the filesystem after before terminating the processes. I have added close and unlink statements at the end, but the fifos are not removed. What am I doing wrong? Thanks very much in advance. P.S.: I am pasting here the whole source file for additional clarity. Just ignore the comments, since they are in my own native language. server.c: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #define MAX_INPUT_LENGTH 100 #define FIFO_NAME_MAX_LEN 20 #define FIFO_DIR "/tmp/" #define FIFO_NAME_CMD_CLI_TO_SRV "lrc_cmd_cli_to_srv" typedef enum { false, true } bool; bool background = false; char* logfile = NULL; void read_from_fifo(int fd, char** var) { int n_bytes; read(fd, &n_bytes, sizeof(int)); *var = (char *) malloc (n_bytes); read(fd, *var, n_bytes); printf("read %d bytes '%s'\n", n_bytes, *var); } void write_to_fifo(int fd, char* data) { int n_bytes = (strlen(data)+1) * sizeof(char); write(fd, &n_bytes, sizeof(int)); //primeiro envia o numero de bytes que a proxima instrucao write ira enviar write(fd, data, n_bytes); printf("writing %d bytes '%s'\n", n_bytes, data); } int main(int argc, char* argv[]) { //CRIA FIFO CMD_CLI_TO_SRV, se ainda nao existir char* fifo_name_cmd_cli_to_srv; fifo_name_cmd_cli_to_srv = (char*) malloc ( (strlen(FIFO_NAME_CMD_CLI_TO_SRV) + strlen(FIFO_DIR) + 1) * sizeof(char) ); strcpy(fifo_name_cmd_cli_to_srv, FIFO_DIR); strcat(fifo_name_cmd_cli_to_srv, FIFO_NAME_CMD_CLI_TO_SRV); int n = mkfifo(fifo_name_cmd_cli_to_srv, 0660); //TODO ver permissoes if (n < 0 && errno != EEXIST) //se houver erro, e nao for por causa de ja haver um com o mesmo nome, termina o programa { fprintf(stderr, "erro ao criar o fifo\n"); fprintf(stderr, "errno: %d\n", errno); exit(4); } //se por acaso já existir, nao cria o fifo e continua o programa normalmente //le informacao enviada pelo cliente, nesta ordem: //1. pid (em formato char*) do processo cliente //2. comando /CONNECT //3. nome de fifo INFO_SRV_TO_CLIXXX //4. nome de fifo MSG_SRV_TO_CLIXXX char* command; char* fifo_name_info_srv_to_cli; char* fifo_name_msg_srv_to_cli; char* client_pid_string; int client_pid; int fd_cmd_cli_to_srv, fd_info_srv_to_cli; fd_cmd_cli_to_srv = open(fifo_name_cmd_cli_to_srv, O_RDONLY); read_from_fifo(fd_cmd_cli_to_srv, &client_pid_string); client_pid = atoi(client_pid_string); read_from_fifo(fd_cmd_cli_to_srv, &command); //recebe commando /CONNECT read_from_fifo(fd_cmd_cli_to_srv, &fifo_name_info_srv_to_cli); //recebe nome de fifo INFO_SRV_TO_CLIXXX read_from_fifo(fd_cmd_cli_to_srv, &fifo_name_msg_srv_to_cli); //recebe nome de fifo MSG_TO_SRV_TO_CLIXXX //CIRA FIFO MSG_CLIXXX_TO_SRV char fifo_name_msg_cli_to_srv[FIFO_NAME_MAX_LEN]; strcpy(fifo_name_msg_cli_to_srv, FIFO_DIR); strcat(fifo_name_msg_cli_to_srv, "lrc_msg_cli"); strcat(fifo_name_msg_cli_to_srv, client_pid_string); strcat(fifo_name_msg_cli_to_srv, "_to_srv"); n = mkfifo(fifo_name_msg_cli_to_srv, 0660); if (n < 0) { fprintf(stderr, "error creating %s\n", fifo_name_msg_cli_to_srv); fprintf(stderr, "errno: %d\n", errno); exit(5); } //envia ao cliente a resposta ao commando /CONNECT fd_info_srv_to_cli = open(fifo_name_info_srv_to_cli, O_WRONLY); write_to_fifo(fd_info_srv_to_cli, fifo_name_msg_cli_to_srv); free(logfile); free(fifo_name_cmd_cli_to_srv); close(fd_cmd_cli_to_srv); unlink(fifo_name_cmd_cli_to_srv); unlink(fifo_name_msg_cli_to_srv); unlink(fifo_name_msg_srv_to_cli); unlink(fifo_name_info_srv_to_cli); printf("fim\n"); return 0; } client.c: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #define MAX_INPUT_LENGTH 100 #define PID_BUFFER_LEN 10 #define FIFO_NAME_CMD_CLI_TO_SRV "lrc_cmd_cli_to_srv" #define FIFO_NAME_INFO_SRV_TO_CLI "lrc_info_srv_to_cli" #define FIFO_NAME_MSG_SRV_TO_CLI "lrc_msg_srv_to_cli" #define COMMAND_MAX_LEN 100 #define FIFO_DIR "/tmp/" typedef enum { false, true } bool; char* nickname; char* name; char* email; void write_to_fifo(int fd, char* data) { int n_bytes = (strlen(data)+1) * sizeof(char); write(fd, &n_bytes, sizeof(int)); //primeiro envia o numero de bytes que a proxima instrucao write ira enviar write(fd, data, n_bytes); printf("writing %d bytes '%s'\n", n_bytes, data); } void read_from_fifo(int fd, char** var) { int n_bytes; read(fd, &n_bytes, sizeof(int)); *var = (char *) malloc (n_bytes); printf("read '%s'\n", *var); read(fd, *var, n_bytes); } int main(int argc, char* argv[]) { pid_t pid = getpid(); //CRIA FIFO INFO_SRV_TO_CLIXXX char pid_string[PID_BUFFER_LEN]; sprintf(pid_string, "%d", pid); char* fifo_name_info_srv_to_cli; fifo_name_info_srv_to_cli = (char *) malloc ( (strlen(FIFO_DIR) + strlen(FIFO_NAME_INFO_SRV_TO_CLI) + strlen(pid_string) + 1 ) * sizeof(char) ); strcpy(fifo_name_info_srv_to_cli, FIFO_DIR); strcat(fifo_name_info_srv_to_cli, FIFO_NAME_INFO_SRV_TO_CLI); strcat(fifo_name_info_srv_to_cli, pid_string); int n = mkfifo(fifo_name_info_srv_to_cli, 0660); if (n < 0) { fprintf(stderr, "error creating %s\n", fifo_name_info_srv_to_cli); fprintf(stderr, "errno: %d\n", errno); exit(6); } int fd_cmd_cli_to_srv, fd_info_srv_to_cli; fd_cmd_cli_to_srv = open("/tmp/lrc_cmd_cli_to_srv", O_WRONLY); char command[COMMAND_MAX_LEN]; printf("> "); scanf("%s", command); while (strcmp(command, "/CONNECT")) { printf("O primeiro comando deverá ser \"/CONNECT\"\n"); printf("> "); scanf("%s", command); } //CRIA FIFO MSG_SRV_TO_CLIXXX char* fifo_name_msg_srv_to_cli; fifo_name_msg_srv_to_cli = (char *) malloc ( (strlen(FIFO_DIR) + strlen(FIFO_NAME_MSG_SRV_TO_CLI) + strlen(pid_string) + 1) * sizeof(char) ); strcpy(fifo_name_msg_srv_to_cli, FIFO_DIR); strcat(fifo_name_msg_srv_to_cli, FIFO_NAME_MSG_SRV_TO_CLI); strcat(fifo_name_msg_srv_to_cli, pid_string); n = mkfifo(fifo_name_msg_srv_to_cli, 0660); if (n < 0) { fprintf(stderr, "error creating %s\n", fifo_name_info_srv_to_cli); fprintf(stderr, "errno: %d\n", errno); exit(7); } // ENVIA COMANDO /CONNECT write_to_fifo(fd_cmd_cli_to_srv, pid_string); //envia pid do processo cliente write_to_fifo(fd_cmd_cli_to_srv, command); //envia commando /CONNECT write_to_fifo(fd_cmd_cli_to_srv, fifo_name_info_srv_to_cli); //envia nome de fifo INFO_SRV_TO_CLIXXX write_to_fifo(fd_cmd_cli_to_srv, fifo_name_msg_srv_to_cli); //envia nome de fifo MSG_TO_SRV_TO_CLIXXX // recebe do servidor a resposta ao comanddo /CONNECT printf("msg1\n"); printf("vamos tentar abrir %s\n", fifo_name_info_srv_to_cli); fd_info_srv_to_cli = open(fifo_name_info_srv_to_cli, O_RDONLY); printf("%s aberto", fifo_name_info_srv_to_cli); if (fd_info_srv_to_cli < 0) { fprintf(stderr, "erro ao criar %s\n", fifo_name_info_srv_to_cli); fprintf(stderr, "errno: %d\n", errno); } printf("msg2\n"); char* fifo_name_msg_cli_to_srv; printf("msg3\n"); read_from_fifo(fd_info_srv_to_cli, &fifo_name_msg_cli_to_srv); printf("msg4\n"); free(nickname); free(name); free(email); free(fifo_name_info_srv_to_cli); free(fifo_name_msg_srv_to_cli); unlink(fifo_name_msg_srv_to_cli); unlink(fifo_name_info_srv_to_cli); printf("fim\n"); return 0; } makefile: CC = gcc CFLAGS = -Wall -lpthread -fno-stack-protector all: client server client: client.c $(CC) $(CFLAGS) client.c -o client server: server.c $(CC) $(CFLAGS) server.c -o server clean: rm -f client server *~

    Read the article

  • Rails - Update a single attribute : link with custom action or form with hidden fields?

    - by MrRuru
    Let's say I have a User model, with a facebook_uid field corresponding to the user's facebook id. I want to allow the user to unlink his facebook account. Do do so, I need to set this attribute to nil. I currently see 2 ways of doing this First way : create a custom action and link to it # app/controllers/users_controller.rb def unlink_facebook_account @user = User.find params[:id] # Authorization checks go here @user.facebook_uid = nil @user.save # Redirection go here end # config/routes.rb ressources :users do get 'unlink_fb', :on => :member, :as => unlink_fb end # in a view = link_to "Unlink your facebook account", unlink_fb_path(@user) Second way : create a form to the existing update action # app/views/user/_unlink_fb_form.html.haml = form_for @user, :method => "post" do |f| = f.hidden_field :facebook_uid, :value => nil = f.submit "Unlink Facebook account" I'm not a big fan of either way. In the first one, I have to add a new action for something that the update controller already can do. In the second one, I cannot set the facebook_uid to nil without customizing the update action, and I cannot have a link instead of a button without adding some javascript. Still, what would you recommend as the best and most elegant solution for this context? Did I miss a third alternative?

    Read the article

1 2 3 4 5 6 7  | Next Page >