IMPORTANT!

Snipt is going open source. We've toyed with this idea for quite a while, and have finally decided it's the right way to move forward.

A few things:
  • The entire Snipt source code will be released on GitHub under the 3-clause BSD License on Friday, September 10th.
  • While we'd like to think we're perfect, we realize we're only human. By open sourcing the software that runs this website, certain bugs or security flaws may be discovered that could compromise the privacy of your snipts.
  • Only the Lion Burger team will be able to push commits to the Snipt.net site. Contributors should send a pull request to add new features or submit patches.
  • By using this site, you agree not to be too angry or take any legal action against Lion Burger should this whole thing go up in flames some day.
  • Follow us on Twitter for updates.
I agree, close this message
Sign up to create your own snipts, or login.

Latest 100 public snipts » file The latest public file snipts.

showing 1-20 of 49 snipts for file
  • An exec <filename command redirects stdin to a file
    19.1. Using exec
    
    An exec <filename command redirects stdin to a file. From that point on, all stdin comes from that file, rather than its normal source (usually keyboard input). This provides a method of reading a file line by line and possibly parsing each line of input using sed and/or awk.
    
    Example 19-1. Redirecting stdin using exec
    
    #!/bin/bash
    # Redirecting stdin using 'exec'.
    
    
    exec 6<&0          # Link file descriptor #6 with stdin.
                       # Saves stdin.
    
    exec < data-file   # stdin replaced by file "data-file"
    
    read a1            # Reads first line of file "data-file".
    read a2            # Reads second line of file "data-file."
    
    echo
    echo "Following lines read from file."
    echo "-------------------------------"
    echo $a1
    echo $a2
    
    echo; echo; echo
    
    exec 0<&6 6<&-
    #  Now restore stdin from fd #6, where it had been saved,
    #+ and close fd #6 ( 6<&- ) to free it for other processes to use.
    #
    # <&6 6<&-    also works.
    
    echo -n "Enter data  "
    read b1  # Now "read" functions as expected, reading from normal stdin.
    echo "Input read from stdin."
    echo "----------------------"
    echo "b1 = $b1"
    
    echo
    
    exit 0
    
    Similarly, an exec >filename command redirects stdout to a designated file. This sends all command output that would normally go to stdout to that file.
    
    Important	
    
    exec N > filename affects the entire script or current shell. Redirection in the PID of the script or shell from that point on has changed. However . . .
    
    N > filename affects only the newly-forked process, not the entire script or shell.
    
    Thank you, Ahmed Darwish, for pointing this out.
    

    copy | embed

    0 comments - tagged in  posted by rschu68 on Jun 23, 2010 at 9:12 a.m. EDT
  • replace string in files
    #!/bin/bash
    for file in *.groovy
    do
      echo "Traitement de $file ..."
      sed -e "s/string1/string2/g" "$file" > "$file".tmp && mv -f "$file".tmp "$file"
    done
    

    copy | embed

    2 comments - tagged in  posted by Bakoi on Jun 16, 2010 at 5:27 a.m. EDT
  • file operations delimiter changer
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main ()
    {
        char data;
        fstream inFile, outFile;
        inFile.open ("A.txt", ios::in);
        if (inFile.fail())
        {
            cout << "File not found!" << endl;
        }
        else
        {
    
            outFile.open("C.txt", ios::out);
            while (!inFile.eof())
            {
                inFile.get(data);
                if (data==';')
                {
                    data=',';
                    outFile<<data;
                }
                else
                    outFile<<data;
            }
            cout<<"Done.";
        }
        outFile.close();
        inFile.close();
    }
    

    copy | embed

    0 comments - tagged in  posted by wafflesncheese on May 14, 2010 at 2:43 a.m. EDT
  • file operations ; delimited output
    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;
    
    int main ()
    {
        string data;
        cout<<"Enter data: ";
        getline(cin,data);
        ofstream outFile; 
        outFile.open ("B.txt"); //open text file
        string::iterator pos;
        for (pos = data.begin(); pos != data.end(); pos++)
        {
            if (*pos==';') //check if character is ';'
            outFile<<endl;
            else
            outFile<<*pos;
        }
        outFile.close();
    }
    

    copy | embed

    0 comments - tagged in  posted by wafflesncheese on May 14, 2010 at 1:42 a.m. EDT
  • file operations ; delimited
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main ()
    {
        char data;
        ifstream inFile;
        inFile.open ("A.txt"); //open text file
        if (inFile.fail()) //check if file is found
        {
            cout << "File not found!" << endl;
        }
        while (!inFile.eof()) //check if it is end of file
        {
            inFile.get(data);
            if (data==';') //check for ';', if true goto next line
                cout<<endl;
            else  //else cout character
                cout<<data;
        }
        inFile.close();
    }
    

    copy | embed

    0 comments - tagged in  posted by wafflesncheese on May 13, 2010 at 4:12 a.m. EDT
  • read admin number
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main()
    {
        ifstream inFile;
    
        inFile.open("test1.txt");
    
        if (inFile.fail())       //check for file existence
        {
           cout << "File does not exist!" << endl;
           cout << "Program exits." << endl;
           cin.get();
           return 0;
        }
    
        //read  data
        char ch1;
        int num;
    
        while (!inFile.eof())    //continue to read and display on screen until EOF
        {
            inFile>>ch1>>num; 
            if (ch1=='P')
            cout<<ch1<<num<<endl;
        }
    
        inFile.close();
        cin.get();              // pause to show screen output
        return 0;
    }
    

    copy | embed

    0 comments - tagged in  posted by wafflesncheese on May 06, 2010 at 10:42 a.m. EDT
  • Magicfields duplicate file fields
    <?php 
    $i = 1;
    $files = get_field_duplicate('pres_file'); 
    foreach ($files as $file) { ?>
    
    <a href="<?php echo $file; ?>">Presentation <?php echo $i++ ?></a>
     <br />
    <?php   
    }
    ?>
    

    copy | embed

    0 comments - tagged in  posted by panprojektant on May 03, 2010 at 5:35 p.m. EDT
  • Prompt user to 'open' or 'save' file when delivering dynamic file data with PHP
    <?
    header("content-type: $mime_type");
    header("content-disposition: attachment; filename=$file_name");
    header("cache-control: private");
    header("pragma: private");
    echo $file_data;
    ?>
    

    copy | embed

    0 comments - tagged in  posted by bradrozier on Apr 26, 2010 at 3:43 p.m. EDT
  • Uploaded file handling with PHP
    <?
    // $_FILES array
    // $_FILES['field_name']['name'] = filename
    // $_FILES['field_name']['type'] = mime type, if provided by browser
    // $_FILES['field_name']['size'] = file size in bytes
    // $_FILES['field_name']['tmp_name'] = temp file name / location
    // $_FILES['field_name']['error'] = error code
    
    if(is_uploaded_file($_FILES['field_name']['tmp_name'])) {
       $file = file_get_contents($_FILES['field_name']['tmp_name']);
       // do something with $file
    }
    ?>
    

    copy | embed

    0 comments - tagged in  posted by bradrozier on Apr 26, 2010 at 3:42 p.m. EDT
  • check for file existence
    if( access( fname, F_OK ) != -1 ) 
    {
        return(TRUE);
    }
    
    else 
    {
        return(FALSE);
    }
    

    copy | embed

    0 comments - tagged in  posted by mrman on Mar 27, 2010 at 10:15 a.m. EDT
  • File uploads in Symfony 1.2, my take
    <?php
    // FILE lib/model/Model.php:
    class Model
    {
      /**
       * Returns the abs path to a subdir of uploads specific for this model.
       *
       * If given a $path, it will be concatenated at the end.
       *
       * @param string $path optional relative path of a file inside the dir
       * @return string      complete path to subdir or file
       */
      public function getUploadPath($path = NULL)
      {
        return sfConfig::get('sf_upload_dir').'/event/' . $path;
      }
    
      /**
       * Returns abs path relative to the docroot.
       *
       * @param string $path
       * @return string
       */
      public function getWebPath($path = NULL)
      {
        return str_replace(sfConfig::get('sf_web_dir'), '', $this->getUploadPath($path));
      }
    }
    
    // FILE lib/form/ModelForm.php:
    class ModelForm extends sfPropelForm
    {
      public function configure() {}
    
      /** 
       * Loops through all form values, updates all files values to be absolute paths relative to the docroot.
       * Calls $model->getWebPath(), but the code is otherwise generally re-usable.
       *  
       * (non-PHPdoc)
       * @see symfony/plugins/sfPropelPlugin/lib/form/sfFormPropel#updateObject($values)
       */
      public function updateObject($values = null)
      {
        $object = parent::updateObject($values);
        foreach ($this->values as $field => $value)
        {
          if ($value instanceof sfValidatedFile)
          {
            $column = call_user_func(array(constant(get_class($object).'::PEER'), 'translateFieldName'), $field, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME);
            $getter = 'get'.$column;
            $setter = 'set'.$column;
            $object->$setter($object->getWebPath($object->$getter()));
          }
        }
        return $object;
      }
    }
    ?>
    

    copy | embed

    0 comments - tagged in  posted by flevour on Mar 25, 2010 at 11:11 a.m. EDT
  • Make file from clipboard data
    package buildfromcbd;
    //
    import java.awt.Toolkit;
    import java.awt.datatransfer.*;
    import java.io.*;
    //
    public class Main {
        //this will be where we split up our values
        private static final String VALUE_SEPARATOR = ":::";
        //
        public static void main(String[] args) throws IOException, UnsupportedFlavorException
        {
           build();
        }
       public static String getClipboard() throws UnsupportedFlavorException, IOException {
           // here we grab the contents of the clipboard
            Transferable tran = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
            try {
                if (tran != null && tran.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                    String text = (String)tran.getTransferData(DataFlavor.stringFlavor);
                    return text;
                }
            } catch (UnsupportedFlavorException e) {
                return "CBD_BUILD_FAILED.txt::: Could not build file, JAVA error report as fallows:\n\n"+e;
            } catch (IOException e) {
                 return "CBD_BUILD_FAILED.txt::: Could not build file, JAVA error report as fallows:\n\n"+e;
            }
            return null;
        }
        public static void build()throws IOException, UnsupportedFlavorException
        {
            Writer output = null;
            String text = getClipboard();
            String[] cbd = parseCBD(text);
            //so our fist value will be our file name
            File file = new File(cbd[0]);
            //lets get our file open for writing now
            output = new BufferedWriter(new FileWriter(file));
            //if cbd has a second value lets write it to our files contents
            if(cbd.length>1)
            {
                output.write(cbd[1]);
            }else{
                 // if we don't have a second value lets print "EMPTY :(" in our file
                output.write("EMPTY :(");
            }
            output.close();
        }
        public static String[] parseCBD(String cb_txt)
        {
            //let's sperate our values out
            String[] cbd = cb_txt.split(VALUE_SEPARATOR);
            //in this function you could do more than just split the data, get creative :)
            return cbd;
        }
    }
    

    copy | embed

    0 comments - tagged in  posted by tafaridh on Feb 26, 2010 at 10:00 p.m. EST
  • VB6: Write a message in a daily log
    Public Sub WriteLog(Message As String)
    
      Dim fso, fileName As String, logString As String, f as Integer
      
      fileName = App.path & "\Log_" & Format(Now, "yyyymmdd") & ".txt"
      logString = Format(Now, "hh:mm:ss") & " - " & Message
      f = Freefile
      Open fileName For Append As #f
      Print #f, logString
      Close #f
    
    End Sub
    

    copy | embed

    0 comments - tagged in  posted by beccoblu on Feb 14, 2010 at 10:04 a.m. EST
  • match my PM list to Hanno's TETRA results
    import sys
    import re
    from sets import Set
    
    f = open ('/Users/user/Downloads/PM-1.txt')
    
    pm_match = re.compile (r'\d+_(\S+)')
    pms = set()
    unique = set()
    
    for line in f.readlines(): 
         pm_result = pm_match.match (line.rstrip())
         
         if pm_result:
            pms.add(pm_result.group(1))
           
            
            
    f.close()
    
    #print pms
    
    matchobj = re.compile (r'(\S+):\s+\d+\.\d+')
    
    f_match = re.compile (r'f_(\d+)[a-z]+_\w+')
    
    a_match = re.compile (r'a4_([0-9a-z]+)_\w+')
    
    for line in sys.stdin:
        names = line.split("\t")
    
        output = ""
        for name in names:
            result = matchobj.match (name)
            
            if result:
    
                #print result.group(1)
                f_result = f_match.match (result.group(1))
                if f_result:
                    PM_name = "fc1f" + f_result.group(1)
                    
                    if PM_name in pms:
                        unique.add(PM_name)          
                
                
                a_result = a_match.match (result.group(1))
                if a_result:
                    PM_name = "anke4-" + a_result.group(1)
                    
                    if PM_name in pms:
                        unique.add(PM_name)
    
    print len(unique)
        #print output.rstrip()
    

    copy | embed

    0 comments - tagged in  posted by dgg32 on Feb 04, 2010 at 10:28 a.m. EST
  • Log errors in diffent folders/files reflecting the application folder structure.
    <?php
    /**
     * Log PHP's error into separate files. Recommended for use in production site.
     * Should be used in set_error_handler() to handle certain PHP errors (i.e. E_STRICT).
     * @link http://www.php.net/manual/en/function.set-error-handler.php Reference
     */
    function errorHandler($errno, $errstr, $errfile=NULL, $errline=NULL, $errcontext=NULL) {
      // Log uncategorized errors
      if (is_null($errfile)) {
        $errfile = 'errors.log';
      }
    
      // Reconstruct the path
      // define('APP_DIR', '/my/application/')
      // define('LOG_DIR', '/log_dir/')
      // E.g. /my/application/controller/index.php -> /log_dir/controller/index.php
      $pos = strpos($errfile, APP_DIR);
      if ($pos !== FALSE) {
        // Strip off the application directory and attach log directory
        $errfile = LOG_DIR.substr($errfile, $pos + strlen(CMS_ROOT));
      }
      else {
        $errfile = LOG_DIR.$errfile; // E.g. /log_dir/errors.log
      }
      $dir = dirname($errfile);
      // Create dir if necessary
      if (! file_exists($dir)) {
        mkdir($dir, 0775, TRUE);
      }
      
      $logFile = fopen($errfile, 'a');
      fwrite($logFile, date('Y-m-d H:i:s ').$errstr);
      if ($errline) fwrite($logFile, " on line $errline");
      fwrite($logFile, "\n");
      fclose($logFile);
      
      if (PRODUCTION_SITE) // Prevent err msg from being printed out (log errors silently)
        return TRUE;
    
      return FALSE;
    }
    ?>
    

    copy | embed

    0 comments - tagged in  posted by hongster on Jan 21, 2010 at 2:46 a.m. EST
  • Usage of Unix fuser
    # Find process associated with a port
    
    $ fuser 80/tcp
    80/tcp:                802   803   804   806   807   808   809   810   811   812   813 23556 23561 23562 23563 23564 23565 23566 23567 23568 28574
    
    # Find process and users associated with a port
    
    $ fuser -nu tcp 80
    80/tcp:                802(apache)   803(apache)   804(apache)   806(apache)   807(apache)   808(apache)   809(apache)   810(apache)   811(apache)   812(apache)   813(apache) 23556(root) 23561(apache) 23562(apache) 23563(apache) 23564(apache) 23565(apache) 23566(apache) 23567(apache) 23568(apache) 28574(apache)
    
    # Kills a process that is locking a file. Useful when you're trying to unmount a volume and other sticky situations where a rogue process is annoying the hell out of you.
    
    $ fuser -k /tmp/blocked_file
    

    copy | embed

    0 comments - tagged in  posted by yvoictra on Jan 17, 2010 at 2:00 p.m. EST
  • Print a file line for line in Java (the 1.6 way)
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    public class SlugTester {
        static String FILENAME = "C:\\slug-test.txt";
        public static void main(String[] args)  {
    
            try  {
                BufferedReader reader = new BufferedReader(new FileReader(FILENAME));
                String line;
                while ((line = reader.readLine()) != null)  {
                    System.out.println(line);
                }
            }
    
            catch (FileNotFoundException e)  {
                e.printStackTrace();
            }
            catch (IOException e)  {
                e.printStackTrace();
            }
        }
    }
    

    copy | embed

    0 comments - tagged in  posted by lenni on Jan 12, 2010 at 4:03 a.m. EST
  • Force file download
    <?php
    header("Content-type: application/octet-stream");
    
    // displays progress bar when downloading (credits to Felix ;-))
    header("Content-Length: " . filesize('myImage.jpg'));
     
    // file name of download file
    header('Content-Disposition: attachment; filename="myImage.jpg"');
     
    // reads the file on the server
    readfile('myImage.jpg');
    

    copy | embed

    0 comments - tagged in  posted by richard on Dec 17, 2009 at 7:59 a.m. EST
  • File object for logging loggers
    To get access to underlying stream (filelike) object in Python's logging system:
    
    logger.handlers[0].stream
    
    You'll have to figure out which handler for a logger object you want. I've only got one in my sample code. This snipt allows one to pass this stream object into interfaces that are expecting a file object.
    

    copy | embed

    0 comments - tagged in  posted by mredar on Dec 16, 2009 at 7:15 p.m. EST
  • Search file by content (improved)
    grep -r 'public static void main(' .
    
    #will do the same thing. In fact, you can also use
    
    grep -rI 'public static void main(' .
    
    #for searching only text files. And if you only want to list the files without the matching content, use
    
    grep -rI –files-without-matches 'public static void main(' .
    

    copy | embed

    0 comments - tagged in  posted by hongster on Nov 12, 2009 at 9:34 p.m. EST
Sign up to create your own snipts, or login.