mercredi 30 septembre 2015

How to send a file in skype to a particular skype user using Java Application?

I want to share a normal file(.pdf, or .doc) to a particular skype user using Java Application. Please let me know how to achieve this.

Can't set variable in generated php code

I have a php script that generates 3 files - 1 .txt and 2 .php. The Script works fine but one thing destroys the idyll, the script did not writes the vars in the 2 generated scripts. (i have also tried . $var . ) Thank you in advance

Best Regards Gd3

The Code:

$filename = uniqid(rand(), true) . '.php';

$fh = fopen($filename, "w+");
    fwrite($fh, "<html><body>
        <div align='center'>
        Neue Nachricht erstellen<br><br>

        <form action='' . $filenamebes . '' Method='post'>

        <input name='Name' size='40'><br><br>


        <textarea name='inhalt' cols='40' rows='12'
        <input type='submit' value='Absenden'>
                    $beitrag = file('' . $filenametxt . '');

                    foreach($beitrag as $ausgabe)
                       $ausgabe = stripslashes($ausgabe);
                       $zerlegen = explode('|', $ausgabe);

                       echo '
                       <table align=\'center\'
                        border=\'1\' cellspacing=\'0\'
                       cellpadding=\'5\' bordercolorlight=\'black\'
                       bordercolordark=\'black\' width=\'50%\'>
                      Titel: <a href=\'mailto:$zerlegen[0]\'>$zerlegen[1]</a>
                      am $zerlegen[2]


$filenametxt = uniqid(rand(), true) . '.txt';
$fhtxt = fopen($filenametxt, "w+");
    fwrite($fhtxt, "");

$filenamebes = uniqid(rand(), true) . '.php';

$fhbes = fopen($filenamebes, "w+");
    fwrite($fhbes, "<html>
<title>Speichere Nachricht</title>

$user = {$_POST['Name']};
$user = htmlentities($user);

$inhalt = {$_POST['inhalt']};
$inhalt = htmlentities($inhalt);
$inhalt = str_replace('\n', '<br>', $inhalt);

$email = {$_POST['EMail']};
$email = htmlentities($email);

if ($inhalt == '' or $user == '')
   echo 'Sie müssen das Feld \'Namen\'
   und \'Inhalt\' ausfüllen';

   $datum= date('d.m.Y H:i:s');


   $datei = fopen('' . $filenametxt . '', 'a');
   fwrite($datei, '\n'.$eintrag);

   echo 'Ihre Nachricht wurde erfolgreich gespeichert';

<a href='' . $filename . ''>Zurück</a>

echo "PHP = $filename TXT = $filenametxt BES = $filenamebes <br><br><a href='".$filename."'>ÖffnenPHP</a> <br><br><a href='".$filenametxt."'>ÖffnenTXT</a> <br><br><a href='".$filenamebes."'>ÖffnenBES</a>"

how to find the same sentences of a file on database of files using java

i have a file and a database in which i have stored files so i want to to find the same sentences of the file on database. so if you show me an interested and easy way to solve this problem. here is my code.

import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;

public class QNoorTest {
    ArrayList al=new ArrayList();
    ArrayList fileNames=new ArrayList();

    Connection con;
    ResultSet rs;

    String username = "root";
    String password = "";
    String url="jdbc:mysql://localhost/Plag";

    public QNoorTest()
        catch(Exception e){


    public ArrayList read(){


            String query="select Files from files";
            rs = con.createStatement().executeQuery(query);            
            String fileName="";

            FileReader fr=new FileReader(String.valueOf(fileNames.get(0)));
            FileReader fr1=new FileReader(String.valueOf(fileNames.get(1)));

            BufferedReader br=new BufferedReader(fr);
            BufferedReader br1=new BufferedReader(fr1);

            String s=br.readLine();
            String s1=br1.readLine();
            int j=0;
                String token[]=s.split("\\.");                

                int i=0;




            String token1[]=s1.split("\\.");
            for(int i=j;i<token1.length;i++){                

        catch(Exception e)
        return al;

   public static void main(String[]args) throws IOException{

       QNoorTest obj=new QNoorTest();

       ArrayList al1 = new ArrayList();
       FileReader fr=new FileReader("E:\\cr.txt");
        BufferedReader br=new BufferedReader(fr);
        String line=br.readLine();
            String token[]=line.split("\\.");
            for(int i=0;i<token.length;i++){

        ArrayList al3 = new ArrayList();
        int counter =0;
        for(int i=0; i<al1.size(); i++){
            for(int j=0; j<al.size(); j++){
        System.out.println("The plagiarized work is "+counter++);

move_uploaded_file doesnt work

I am trying to upload an image via php script.

in script all conditions are true while i upload image but move_uploaded_file function doesnt seem to work

what may be the problem?? Help me

My HTML code is

<form id="register_form" action="" method="post" enctype="multipart/form-
Select image to Upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">

PHP Script:

$target_dir = "/home/infibusiness1/Desktop/uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
} else {
    echo "File is not an image.";
    $uploadOk = 0;

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], 
$target_file)) {
    echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has   
been uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
echo "<br>File Name : ".$_FILES['fileToUpload']['tmp_name'];

Java execute file relative to jar

I have a c# console application I will be sending commends to using Java, with the techniques described here Sending commands to a console application?

My issue is that the console application is in a folder that's in the same folder with the jar, and I can't find out how to execute a file relative to the same directory as the jar.

I tried a lot of things in Java, like

Process pr = Runtime.getRuntime().exec("runtime_libraries/consoleapp.exe");

But it says the file can't be found. CreateProcess error=2, The system cannot find the file specified

I assumed it would be simple, but apparently it's not.

So my question is, how can I put a relative path into the Runtime exec?

C# writing and reading a text file

using System; using System.IO; namespace Assignment1 { class Program // reused test 3 - V1 solution { static string GetString(string prompt, string error) { string data = ""; while (data == "") { Console.Write(prompt); data = Console.ReadLine(); if (data == "") Console.WriteLine(error); } return data; } static int GetUsage(string prompt, string error, int n1, int n2, int n3, int n4, int n5, int n6) { int data = -1; while (data == -1) { Console.Write(prompt); if (int.TryParse(Console.ReadLine(), out data) == false) data = -1; else if (data != n1 && data != n2 && data != n3 && data != n4 && data != 5 && data != n6) data = -1; if (data == -1) Console.WriteLine(error); } return data; } static decimal GetPlan(string Plan) { const decimal PRICES = 55, PRICEM = 70, PRICEL = 95, PRICEXL = 135; decimal Fee = 0; if (Plan.ToLower() == "s") Fee = PRICES; else if (Plan.ToLower() == "m") Fee = PRICEM; else if (Plan.ToLower() == "l") Fee = PRICEL; else Fee = PRICEXL; return Fee; } static void DisplayCustomer(string FullName, string Address, string Reference, string Plan) { Console.WriteLine("\nTo: {0} - Reference No: {1}\nAddress: {2}\n\n{3,-40}$ {4,8:f}\n", FullName, Reference, Address, "Monthly Payment for \"" + Plan.ToUpper() + "\":", GetPlan(Plan)); }

    static float GetPlan(string Plan, float DataBlock)
        DataBlock = 0;
        const float DATAS = 1, DATAM = 2.5F, DATAL = 6, DATAXL = 10;
        switch (Plan)
            case "S":
            case "s": DataBlock = DATAS; break;
            case "M":
            case "m": DataBlock = DATAM; break;
            case "L":
            case "l": DataBlock = DATAL; break;
            case "XL":
            case "xl": DataBlock = DATAXL; break;
        return DataBlock;

    static void AddCustomer(string[] CustomerName, string[] CustomerAddress, string[] CustomerReference, string[] CustomerPlan, ref int current, ref int last)
        string FullName, Address, Reference, Plan;
        // Clear the previous customer details
        FullName = Address = Reference = Plan = ""; //set to empty status to enforce go thru the loop
        int TempBlock;
        while (FullName == "")
            FullName = GetString("\nFull Name: ", "Full Name can't be EMPTY");
            for (int i = 0; i < FullName.Length; i++)
                if (Char.IsDigit(FullName[i]))
                    Console.WriteLine("Full Name can't have digit");
                    FullName = ""; // set to go back get new Name input
                    i = FullName.Length; // stop the loop
        while (Address == "")
            Address = GetString("Address: ", "Full Name can't be blank ");
            if (!Char.IsDigit(Address, 0))
                Console.WriteLine("Full Name should be have home number is numeric characters only\n");
                Address = "";
        while (Reference == "")
            Reference = GetString("Reference Number: ", "Reference can't be blank");
            if (int.TryParse(Reference, out TempBlock) == false)
                Console.WriteLine("Reference should be numeric characters only\n");
                Reference = "";
        while (Plan == "")
            Plan = GetString("Current Plan (S, M, L or XL): ", "Plan can't be Blank").ToUpper();
            if (Plan != "S" && Plan != "M" && Plan != "L" && Plan != "XL") Plan = "";
        // store input to array at last position
        CustomerName[last] = FullName;
        CustomerAddress[last] = Address;
        CustomerReference[last] = Reference;
        CustomerPlan[last] = Plan;
        current = last; // current is the entered record
        last++; // increase the last count by 1

    static void FindCustomer(string[] CustomerName, string[] CustomerAddress, string[] CustomerReference, string[] CustomerPlan, ref int current, int last)
        string sname = GetString("Enter the search name: ", "Search Name can't be blank");
        int i;
        for (i = 0; i < last; i++)
            if (CustomerName[i].ToLower().Contains(sname.ToLower()))
                DisplayCustomer(CustomerName[i], CustomerAddress[i], CustomerReference[i], CustomerPlan[i]);
                string confirm = GetString("Is that record you search for (y/n)? ", "please enter confirmation");
                if (confirm.ToUpper() == "Y")
                    current = i;
        if (i == last) Console.WriteLine("{0} is not on the Customer list", sname);

    static void CalculateDisplayPay(string[] CustomerName, string[] CustomerAddress, string[] CustomerReference, string[] CustomerPlan, int current, ref int email)
        // declare constants for prompt
        const string Heading = "\nData Calculate\n\nIn a typical per Day, how often do you do these activities\nwhile you're not connected to Wi-Fi?\n\n";
        const string EWUnit = "\n0\t5\t25\t50\t100\t250+\n";
        const string TimeUnit = "\n0\t5min\t15min\t30min\t45min\t1hr+";
        const string EmailPrompt = "Emails:" + EWUnit + "How many emails (without attachment) do you send/receive? ";
        const string WebPrompt = "\nWeb Browsing:" + EWUnit + "How many pages do you visit (including Facebook)? ";
        const string VideoPrompt = "\nVideo / movie streaming:" + TimeUnit + "\nHow much time do you spend watching videos? ";
        const string MoviePrompt = "\nHD movies:\n0\t1\t2\t3\t5\t15\nHow many HD movies do you download? ";
        const string MusicPrompt = "\nMusic:" + TimeUnit + "\nHow much music do you stream or download? ";
        const string AppPrompt = "\nApps / games:\n0\t1\t2\t3\t6\t10+\nHow many apps or games do you download? ";

        // constant average
        const float EMAIL = 0.02731f, WEB = 0.38912f, VIDEO = 3.00373f, MOVIE = 68.26667f, MUSIC = 1.00124f, APP = 34.98667f, ROUND = 0.009f;
        const int DAYS = 30, GB = 1024, PERCENT = 100;

        const decimal EXTRA = 10;
        decimal Fee = 0, ExtraPay = 0, Payment = 0;
        int TempBlock = 0;
        float DataBlock = 0;

        int web, video, movie, music, app;
        email = web = video = movie = music = app = -1; // set to invalid status to enforce go thru validation
        email = GetUsage(EmailPrompt, "Invalid Emails data - Try again...\n", 0, 5, 25, 50, 100, 250);
        web = GetUsage(WebPrompt, "Invalid Web Page data - Try again...\n", 0, 5, 25, 50, 100, 250);
        video = GetUsage(VideoPrompt, "Invalid Video data - Try again...\n", 0, 5, 15, 30, 45, 1);
        movie = GetUsage(MoviePrompt, "Invalid Movie data - Try again...\n", 0, 1, 2, 3, 5, 15);
        music = GetUsage(MusicPrompt, "Invalid Music data - Try again...\n", 0, 5, 15, 30, 45, 1);
        app = GetUsage(AppPrompt, "Invalid Apps / Games data - Try again...\n", 0, 1, 2, 3, 6, 10);
        if (video == 1) video = 60;
        if (music == 1) music = 60;

        // Calculate total
        float TotalEmail = email * EMAIL * DAYS / GB;
        float TotalWeb = web * WEB * DAYS / GB;
        float TotalVideo = video * VIDEO * DAYS / GB;
        float TotalMovie = movie * MOVIE * DAYS / GB;
        float TotalMusic = music * MUSIC * DAYS / GB;
        float TotalApp = app * APP * DAYS / GB;

        float Total = TotalEmail + TotalWeb + TotalVideo + TotalMovie + TotalMusic + TotalApp;
        Fee = GetPlan(CustomerPlan[current]);
        DataBlock = GetPlan(CustomerPlan[current], DataBlock);
        // set default no extra block //Test 2 calculate - (4 * 3 marks + 2 marks = 10 marks)
        double extra = Total - DataBlock; // find the different
        if (extra < 0) TempBlock = 0;
        else if (extra - (int)extra > 0) TempBlock = (int)extra + 1; // any extra point will round to next GB
        else TempBlock = (int)extra; // if whole value do not need to round - but change to int type to store
        ExtraPay = TempBlock * EXTRA;
        Payment = Fee + ExtraPay;

        // Display Output 
        // Test 2 output 6 * 2 marks = 12 marks
        Console.WriteLine("\n\n\nTo: {0} - Reference No: {1}\nAddress: {2}", CustomerName[current], CustomerReference[current], CustomerAddress[current]);
        Console.WriteLine("\nBased on your answers, your estimated data usage per month is: {0:f}GB per month\n", Total + ROUND);
        Console.WriteLine("{0,-40}$ {1,8:f}\nData Plan: {2} GB - Extra Block(s): {3} GB @ $ {4:f}\n{5,-40}$ {6,8:f}\n{7,-40}$ {8,8:f}\n",
                             "Monthly Payment for \"" + CustomerPlan[current].ToUpper() + "\":", Fee, DataBlock, TempBlock, EXTRA, "Extra Data Usage: ", ExtraPay, "Payment Due: ", Payment);
        // output results
                             , "Emails", Math.Round(TotalEmail / Total * PERCENT)
                             , "General browsing", Math.Round(TotalWeb / Total * PERCENT)
                             , "Video / Movie streaming", Math.Round(TotalVideo / Total * PERCENT)
                             , "HD Movie", Math.Round(TotalMovie / Total * PERCENT)
                             , "Streaming music", Math.Round(TotalMusic / Total * PERCENT)
                             , "Downloading apps", Math.Round(TotalApp / Total * PERCENT));


    static void RemoveCustomer(string[] CustomerName, string[] CustomerAddress, string[] CustomerReference, string[] CustomerPlan, ref int current, ref int last)
        DisplayCustomer(CustomerName[current], CustomerAddress[current], CustomerReference[current], CustomerPlan[current]);
        string confirm = GetString("Is that record you search for (y/n)? ", "please enter confirmation");
        if (confirm.ToUpper() == "Y")
            for (int i = current; i < last - 1; i++)
                CustomerName[i] = CustomerName[i + 1];
                CustomerAddress[i] = CustomerAddress[i + 1];
                CustomerReference[i] = CustomerReference[i + 1];
                CustomerPlan[i] = CustomerPlan[i + 1];
    static void WriteToFile(string[] CustomerName, string[] CustomerAddress, string[] CustomerReference, string[] CustomerPlan, ref int current, ref int howmany)
            FileStream fs =new FileStream("product.txt",FileMode.Create,FileAccess.Write);
            StreamWriter sw =new StreamWriter(fs);
            int i;
            for( i = 0; i < howmany-1; i++) sw.WriteLine("{0},{1},{2},{3},{4}", CustomerName[i],CustomerAddress[i],CustomerReference[i],CustomerPlan[i]);
            sw.Write("{0},{1},{2},{3},{4}", CustomerName[i], CustomerAddress[i], CustomerReference[i], CustomerPlan[i]);
        catch (Exception error)
            Console.WriteLine("Error! cant' create product Text file - {0}", error.Message);
    static void GetFileData(string[] CustomerName, string[] CustomerAddress, string[] CustomerReference, string[] CustomerPlan, ref int current, ref int howmany)
                Console.WriteLine("Warning.... All current data will be overrided by new file data");
                string response = GetString("Do you want to load new data set (y/n)? ","Invalid-input is y or n ONLY");
                if (response.ToLower() == "n") return;
            FileStream fs = new FileStream("product.txt", FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs);
            string line = sr.ReadLine();
            while(line!= null)
                string[] record= line.Split(',');
                Console.Write("{0},{1},{2},{3},{4}", CustomerName[0], CustomerAddress[0], CustomerReference[0], CustomerPlan[0]);
        catch (Exception error)
            Console.WriteLine("Error! cant' open product Text file - {0}", error.Message);

    static void Main()
        // Test 1 input data
        int email = -1;

        // Assignment 1
        const int size = 3;
        string[] CustomerName = new string[size];
        string[] CustomerAddress = new string[size];
        string[] CustomerReference = new string[size];
        string[] CustomerPlan = new string[size];
        int current = 0, last = 0;

        string Option = "a"; // set default to first one
        while (Option != "x")
            // display menu
            Console.WriteLine("\nMenu Option\nAdd a customer (a)\nDisplay current customer (d)\nFind a customer (f)\nCalculate and display payment for current customer (c)\nRemove current customer (r)\nExit (x)\n");
            // get selection Option
            Option = GetString("Enter your Option(a, d, f, c, r or x)? ", "Please selection one of the correct option");
            // perform Option Input
            switch (Option)
                case "a":
                case "A":
                    if (last == size) Console.WriteLine("Array is full");
                        if (email != -1) email = -1; // also clear previous customer bill to avoid display the wrong bill in d option
                        AddCustomer(CustomerName, CustomerAddress, CustomerReference, CustomerPlan, ref current, ref last);

                case "d":
                case "D":
                    if (last == 0) Console.WriteLine("No record to display");
                    else DisplayCustomer(CustomerName[current], CustomerAddress[current], CustomerReference[current], CustomerPlan[current]);

                case "f":
                case "F":
                    if (last == 0) Console.WriteLine("No record to search for");
                    else FindCustomer(CustomerName, CustomerAddress, CustomerReference, CustomerPlan, ref current, last);

                case "c":
                case "C":
                    if (last == 0) Console.WriteLine("No record to Calculate usage");
                    else CalculateDisplayPay(CustomerName, CustomerAddress, CustomerReference, CustomerPlan, current, ref email);

                case "r":
                case "R":
                    if (last == 0) Console.WriteLine("No record to delete");
                    else RemoveCustomer(CustomerName, CustomerAddress, CustomerReference, CustomerPlan, ref current, ref last);
                case "s":
                case "S":
                    if (current == 0) Console.WriteLine("No record to write to file");
                    else WriteToFile(CustomerName, CustomerAddress, CustomerReference, CustomerPlan,current,);
                case "i":
                case "I":
                    GetFileData(CustomerName, CustomerAddress, CustomerReference, CustomerPlan, ref current, ref howmany);
                case "x":
                case "X": Console.WriteLine("End of the program\n");
                    Option = Option.ToLower(); // enforce to stop the loop condition
                default: Console.WriteLine("Unknown option - Try again\n"); break;
            } // end of Option performance
        }  // end of while loop for menu   


There is an error in writing and reading the file ( error in the code which is hard for me to correct) can any one help me out

Why does pyserial read as b'number'

I want to save those values in a file.txt, when the program saves them, it saves b'number', I'd like to plot those values but I can't with b'number' I just want number saved

Write function fcopy() that takes two file name inputs and copies the content of the first file into the second using Python

So I did:

def fcopy(original, copy):
'creates a copy of file original named copy'
    infile = open(original)
    content =

But this only print out what's in the original file. No clue how to copy the content of original to the copy file.

How to get list of files from an SFTP server?

I have a problem and hoping to get a solution. I also have written some code but it needs some modification.

Problem: I have a SFTP server (for privacy purposes I will give dummy credentials) that I need to connect to.

Server name: server-name port: 22 username: username password: password

When I connect to the server, it automatically drops me in the "/FGV" directory. inside this directory are couple other folders. I need to grab a LIST of xml messages from the "/FGV/US/BS/" directory and place them in a LIST (files in the form of File). In the list, I need to have the directory of the file, file name and the file body. I was thinking of creating an object and putting this information in there and creating a List of that object.

My current code creates a connection and downloads only ONE xml file. If there are two xml files, then the file in my local machine has nothing as content.


import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class SFTPinJava {

public SFTPinJava() {

public static void main(String[] args) {
    String SFTPHOST = "server-name";
    int SFTPPORT = 22;
    String SFTPUSER = "username";
    String SFTPPASS = "password";

    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        channel = session.openChannel("sftp");
        channelSftp = (ChannelSftp) channel;;
        byte[] buffer = new byte[1024];
        BufferedInputStream bis = new BufferedInputStream(
        File newFile = new File(
        OutputStream os = new FileOutputStream(newFile);
        BufferedOutputStream bos = new BufferedOutputStream(os);
        int readCount;
        //System.out.println("Getting: " + theLine);
        while ((readCount = > 0) {
            //System.out.println("Writing: ");
            bos.write(buffer, 0, readCount);

        while(session != null){
            System.out.println("Killing the session");

    } catch (Exception ex) {


I need to change this code so that it would grab multiple files and puts them in a list of objects. that object should have the directory of the file, the file name and the body of the file.

Can somebody help me out?

Thanks in advanced.

Ruby File.exist? always return false even when file does exist

I have this really small program written in Ruby that tries to open a file:

puts "Enter file name: ";
relPath = gets;
absPath = Dir.pwd << "/" << relPath;
if File.exist?(absPath) then
    puts "File exists";
    file =, "r");
    other code...
    puts "File does not exist";

The problem is that it always prints File does not exist even when the current directory exists and the file also exists. The file and script are in the same directory. I am running it on Mac OS X Yosemite (10.10.3) and Ruby 2.2.0p0

Filename increment in applescript

I'm after a lightweight automator process (applescript) to detect filenames like "file_v01", "document_v03" all ending in "_vXX" to be incremented (to "file_v02" and there is suprisingly little content out there on this.

I have attempted simply detecting and removing the last two characters from the filename to no avail, and any thoughts would be great. Doesnt need to be anything fancy, just v_02 becomes v_03.

Any help would be great!!

Fastest way to check if an image sequence string actually exists on disk

I have a potentially big list of image sequences from nuke. The format of the string can be:



/path/to/img_seq.%0id[.suffix].ext, i being an integer value, the values between [] being optional.

The question is: given this string, that can represent a sequence or a still image, check if at least one image on disk corresponds to that string in the fastest way possible.

There is already some code that checks if these files exist, but it's quite slow.

First it checks if the folder exists, if not, returns False

Then it checks if the file exists with os.path.isfile, if it does, it returns True.

Then it checks if no % or # is found in the path, and if not os.path.isfile, it returns False.

All this is quite fast.

But then, it uses some internal library which is in performance a bit faster than pyseq to try to find an image sequence, and does a bit more operations depending if start_frame=end_frame or not. But it stills take a large amount of time to analyze if something is an image sequence, specially on some sections of the network and for big image sequences.

For example, for a 2500 images sequence, the analysis takes between 1 and 3 seconds.

If I take a very naive approach, and just checks if a frame exist by replacing #### by %04d, and loop over 10000 and break if found, it takes less than .02 seconds to check for os.path.isfile(f), specially if the first frame is between 1-3000. Of course I cannot guarantee what the start frame will be, and that approach is not perfect, but in practice many of the sequences do begin between 1-3000, and I could return True if found and fallback to the sequence approach if nothing is found (it would still be quicker for most of the cases)

I'm not sure what's the best approach is for this, I already made it multithreaded when searching for many image sequences, so it's faster than before, but I'm sure there is room for improvement.

fortran function to find available file unit

I can write a FORTRAN function to find an available file unit, but I was certain there was already an intrinsic. But if there is, I can't find anything about it. Is there such a thing or am I dreaming?

How to Check the Integrity of a SQL Server Backup File?

In Micrsooft SQL Server is there a way to test the integrity of a database backup file without having to restore it to see if it works?

I've looked through the SQL 2014 Management Studio UI and don't see a Test option exposed there.

I've filtered through the Restore Options page and haven't been able to pinpoint anything useful there.

Also I've done some searching on the Internet. Maybe it's due to the generic wording of the search items but I haven't come up with anything yet except how to restore databases.

Virtual File Name too long

I'm using the <() on bash to create virtual files. I'm basically dumping strings into it so I would get <(contents of string), however, the strings are too long and I get this error

:error:0200103F:system library:fopen:File name too long:bss_file.c:391.

Any suggestions on how I can prevent this when creating the virtual file?


Convert code from ftp to sftp in a batch file

I need to convert code in a batch file from ftp to sftp. The current code is ftp -id -s:s:\ftpFPCert.txt . How do I rewrite it to sftp ?

JGit Error-> Caused by: java.lang.NoSuchMethodError: No virtual method toPath()

I am trying clone a repository on Android Java but I get an error when I call the method:

Apparently the File object has not toPath() method.

public void gitClone() throws GitAPIException {

    // File dir = new File(_ctx.getExternalFilesDir(null) + File.separator + "openshift_files");
    Bundle b2 = getIntent().getExtras();
    //File localPath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
    final File localPath = new File(getExternalFilesDir(null) + File.separator + getCurrentApp().getName());

            .setCredentialsProvider(new UsernamePasswordCredentialsProvider(b2.getString("OPEN_SHIFT_USER"), b2.getString("OPEN_SHIFT_PASSWORD")))

This is the stack trace

E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #5
E/AndroidRuntime: Process: com.javier.openshift, PID: 22919
E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime:     at android.os.AsyncTask$3.done(
E/AndroidRuntime:     at java.util.concurrent.FutureTask.finishCompletion(
E/AndroidRuntime:     at java.util.concurrent.FutureTask.setException(
E/AndroidRuntime:     at
E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$
E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(
E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$
E/AndroidRuntime:     at
E/AndroidRuntime:  Caused by: java.lang.NoSuchMethodError: No virtual method toPath()Ljava/nio/file/Path; in class Ljava/io/File; or its super classes (declaration of '' appears in /system/framework/core-libart.jar)
E/AndroidRuntime:     at org.eclipse.jgit.util.FileUtil.exists(
E/AndroidRuntime:     at org.eclipse.jgit.util.FS_POSIX.exists(
E/AndroidRuntime:     at
E/AndroidRuntime:     at<init>(
E/AndroidRuntime:     at
E/AndroidRuntime:     at
E/AndroidRuntime:     at org.eclipse.jgit.api.CloneCommand.init(
E/AndroidRuntime:     at
E/AndroidRuntime:     at com.javier.apps.AppsActivity.gitClone(
E/AndroidRuntime:     at com.javier.apps.AppsActivity$AsyncTaskCloneRepository.doInBackground(
E/AndroidRuntime:     at com.javier.apps.AppsActivity$AsyncTaskCloneRepository.doInBackground(
E/AndroidRuntime:     at android.os.AsyncTask$
E/AndroidRuntime:     at
E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$ 
E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker( 
E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$ 
E/AndroidRuntime:     at 

Checking existance of a file on web server using server-side Javascript

I am generating html code using JavaScript on a web server and the html contains an object that has an id "ImageID" and a src parameters pointing to "Picture1.jpg".

I want to refresh the web page every 5 seconds and use Javascript to generate a new file path using incrementing numbers to say "Picture2.jpg" or "Picture3.jpg" but I want to use the Javascript to check whether such a new file name exists on the server before trying to refresh the img object using


How can server-side JavaScript be used to test the existence of a particular server-side file?

Is these a simple FileExists() method or does the object returned by document.getElementById(ImageName) have to be queried somehow to find out if it successfully found the file or not.

Thanks everyone.

How to write a file in specific path in ruby

I want to save my files in specific path.. I have used like this file_name = gets F = open.(Dir.pwd, /data/folder /#{@file_name },w+) I'm not sure whether the above line is correct or not! Where Dir.pwd tell the directory path followed by my folder path and the file name given.

It should get store the value on the specific path with the specific file name given..Can anyone tell me how to do that..Thanks in advance

Read text file into vector (double, double, string)? C++

I have a text format that uses latitude, longitude and name of location , for example:

41.3333 34.3232 Old Building

I have to read this text file (from the command line), split each line by white space, use stod to convert the lat and long back into a double, then read the whole file into a vector or a list.

This is what I currently I am stuck on:

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

class Distance{
    double x;
    double y;
    string location;

int main(int argc, char *argv[]){
    // If the user didn't provide a filename command line argument,
    // print an error and exit.
    if (argc <= 1){
        cout << "Usage: " << argv[0] << " <Filename>" << endl;

    char *pFilename = argv[1];

    string buf; // Have a buffer string
    stringstream ss(argv[1]); // Insert the string into a stream
    vector<string> tokens; // Create vector to hold our words

    while (ss >> buf)


  1. Could I have some insight on how to proceed with the implementation?

Answer: from here I need to look at each line in the file and split them by whitespace then store the file in a vector by what they are. So the first number of the text file would be latitude, second longitude, and third (string) is location.

How to load a resource from an Uri containing its assembly and path from any assembly?

I want to load any resource from any assembly (of the same app) using only its uri. Both assemblies are part of the same application.

Because I want to be able to load from any assembly, I can't use "App" or "Application" which is not defined in a general Dll.

I think part or the answer is using : System.Reflection.Assembly.GetCallingAssembly().GetManifestResourceStream(path);

But I can't find how to properly find/extract/resolve the assembly from the uri?


  • The resource is actually defined as "Resource".
  • The resource is not par of a WPF resource dictionary.
  • The resource is actually an XML file but could be anything

Up to now (~3 hours after), after using reflector, it seems that using static System.Windows.Application.GetResourceStream(uri).Stream has advantages like resource caching. It is bad because it is hooked to WPF ( I'm looking for a better way (non depending on any specific UI framework) to do the job.

How to fix / recover all files which are encrtyped by .krypted extension

In my computer all of my files (eg. doc, docx, jpg etc..) name ended with .krypted extension, like my_picture.jpg.krypted. When I open it, it's showing my encrypted key. So that, I can't see my original file. It's affected on all of my pictures, files. How can I recover my files which are encrypted with .krypted extension ?

Note: I am using windows 10

MDLS | MetaData | Unable to grab kMDItemVersion of Illustrator File

I'm attempting to display a files version using mdls -name kMDItemVersion filepath but it's returning null.

If I simpy run mdls filepath the kMDItemVersion is not displayed for the file.

The weird part is that I can view the version info by right-clicking and selecting get info.

Normally I would use kMDItemCreator but .ai files don't appear to add that specific metadata unlike most other apps.

Sadly I don't have enough points to post pics. It's important to know that the .ai files clearly displays the following under get info > general.

Version: Saves As v.17 Created by v. 18.0.0

This is exactly the info I'm after.

Links to pics below. Any assistance is greatly appreciated.

Java Uploaded file is not the same

my problem is the following, I'm trying to upload a file to my server via servlet but the uploaded file is not the same, it has differentes compared to the original one.

For example, If I upload TXT file for example

# Root logger option
log4j.rootLogger=DEBUG, stdout, file

# Redirect log messages to console
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p     %c{1}:%L - %m%n

# Rirect log messages to a log file
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p         %c{1}:%L - %m%n

The upload file has a new line with


(Opened with Notepad++).

If the file is a .exe, the uploaded file doesn't work.

My code is the following

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        System.out.println("ES UN REQUEST MULTIPART " + isMultipart);
        // Set factory constraints
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();
        // Set overall request size constraint
        // Parse the request
        // List / FileItem / items = upload.parseRequest(request);
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            // FileItem item = (FileItem);
            FileItemStream itemS = (FileItemStream);

            if (itemS.isFormField() == false) {
                // Process a file upload
                String fileName = itemS.getName();
                System.out.println("FILE NAME " + fileName);
                // Process a file upload
                File uploadedFile = new File("C:\\FilesUpload\\" + UUID.randomUUID());
                // InputStream uploadedStream = item.getInputStream();

                FileOutputStream fout = new FileOutputStream(uploadedFile);
                BufferedOutputStream bout = new BufferedOutputStream(fout);
                BufferedInputStream bin = new BufferedInputStream(itemS.openStream());
                byte buf[] = new byte[2048];
                Long contador = 0L;
                while (( != -1) {
                    contador = contador + 1L;
    } catch (Exception e) {

find all the method from the given input java.file

Is there way find all the name method from the given input java.file?

File f = new File(C:\;

.getAbsoultePath prints the ProjectPath instead of SystemPath?

There is a little Problem with the file.getAbsolutePath() method and I tried also the f.getcanonicalPath(); method.

Instead of

C:/Documents and Settings

it prints

C:\Users\me\Documents\NetBeansProjects\fileC\Documents and Settings

Could you maybe explain how it should be changed ?

Thank you

    f = new File(C://);
    fs = f.list();

    for(String fsv : fs) {
     f = new File(fsv);
     String ap = f.getAbsolutePath();

Cordova android fileEntry.moveTo error

I need to rename a video after i capture it with media-capture plugin. After some reading i understood that it should be done via moveTo method. Here is some code:

   window.resolveLocalFileSystemURL('cdvfile://localhost/root/storage/ext_sd/DCIM/100MEDIA/VIDEO0045.mp4', function(f){
      file.getParent(function(dir) {
      file.moveTo(dir, "bla.mp4", function(e){
      }, function(e){
    }, function(e){
  }, function(e){

So, file is found, dir is found too (both resolveLocalFileSystemURL calls are resolved with FileEnrty and DirectoryEntry). But file.moveTo invocation fails with error code 1 ('file not found' as far as i remember).

In my manifest file there is a permission WRITE_EXTERNAL_STORAGE

What can be wrong?

Batch File: Removing carriage return from .tsv file

I am trying to remove carriage return from .tsv file using batch file. This is how my .tsv file looks, the first line is a column line

Class   Name & Address  Item    lbs Value   Pickup/Drop off Date:   23 Sep
 1st Class  Ben Coha
 2305 E LA AVE
 93292-4439 Health and beauty product / cologne body wear for men   0.13    19      
Priority    mich marce
 2505 rid court
 prince frick, MD
 20678  health and beauty product / cologne body wear for women 1.5 47  

I want this file as below (I used notepad to replace \r)

Class   Name & Address  Item    lbs Value   Pickup/Drop off Date:   23 Sep
1st Class   Ben Coha 2305 E LA AVE VISIA, CA 93292-4439 Health and beauty product / cologne body wear for men   0.13    19      
Priority    mic marce 2505 rid court prince frick, MD 20678 health and beauty product / cologne body wear for women 1.5 47  

I tried following batch file. file is being put in one single line. It removes both carriage return and line feed.

@echo off
SetLocal DisableDelayedExpansion
for /f "delims=" %%a in (myFile.tsv) do (
echo/|set /p ="%%a%"

The result looks like..

Class   Name & Address  Item    lbs Value   Pickup/Drop off Date:   23 Sep1st Class Ben Coha 2305 E LA AVE VISIA, CA 93292-4439 Health and beauty product / cologne body wear for men   0.13    19      Priority    mic marce 2505 rid court prince frick, MD 20678 health and beauty product / cologne body wear for women 1.5 47  

I want to modify the .bat file so that it only removes \r instead of removing both \r\n

Excel formulas are not updating with data from an external file unless the external file is open

I have created an excel sheet which references an external excel file/sheet. A problem I am having is that many formulas I have in my sheet do not update with information unless I open the external file at the same time. I'm sure there will be a setting somewhere to fix this but I would like this sheet to update without having to open the other excel file?

How to avoid saving a file on hard drive?

Each time I run the following code, the file is saved on a hard drive. However, I want it to be saved only in the Object Storage container.

OSClient os = OSFactory.builder()

        String containerName = "MyImgs";
        String objectName = "test.jpg";

BufferedWriter output = null;
        try {
            File f = new File(objectName);
            output = new BufferedWriter(new FileWriter(f));
            String etag = os.objectStorage().objects().put(containerName, 
        } catch ( IOException e ) {

Fscanf does not care about endofline

I want to read int from a file

The first line is composed of 1 int and the second of 2


 2 3

if i do

 fscanf(FILE, "%d \n %d %d", &a, &b, &c);

I obtain correctly the 3 numbers but if i put all the numbers on the same line in the file ie 1 2 3

I obtain the same result (and that's not what i want)

I want to know : How to force the user to go to a new line in his file ?

File content changes when copied to another file

I am parsing database file based on VisualFoxPro database(.dbf file),all data are assembled into just one file with tags in between telling where the files are splited.I have written codes to split files in to simple files,which is just the form VisualFoxPro creates it.But VFP can not parse the file.

I find out that when I open a fine file I just created from VisualFoxPro,everything goes well.But the file can't be read after a copied all characters to another file.I tried this in notepad++,MS notepad,MS word, the results are the same(the hex file are just the same before and after,but still cna be parsed). Also I see lots of "NUL"s in notepad++, they just disappeared when I copy and paste the file into new file.What could go wrong?

What opens a file.dtb for editing and save?

I have been looking for a software that opens .dtb file extention, a software for windows 7 64 bit, nothing of what I found really works for editing and saving, any idea?

How do I write specific part of text file to an other in Java?

I have text file that contains lots of text and I want only text between script script tags to be written to an other text file.

So far i have only this where i read the text from the file and write it to other an other text file. But I want to only write certain part to the text to new text file. Part is between "script" "/script" in the original text file.

public static void main(String args[]) {
    FileReader fr = null;
    FileWriter fw = null;
    try {
        fr = new FileReader("1.txt");
        fw = new FileWriter("2.txt");
        int c =;
        while(c!=-1) {
            c =;
    } catch(IOException e) {
    } finally {
public static void close(Closeable stream) {
    try {
        if (stream != null) {
    } catch(IOException e) {


Reactjs, Loopback, Google Cloud storage and file download

Requirement: Let the user download a file when they click a button in the ReactJS page. The react application talks to loopback which then gets the file from GCS. I have a requirement to let the user download - .pdf, .doc, .docx, .txt and .html files.

Problem: The below code works when I try to download .txt and .html files. The others don't work. I can see the data coming across for .pdf, .doc, .docx to the browser but the applications don't display the data properly.

In Loopback API:

var concat = require('concat-stream');
var gcloud = require('gcloud');

var gcs ={
  keyFilename : './keyfile.json',
  projectId : 'PROJECT_ID'

UploadActivity.downloadFilesFromGCS = function(ctx, res, cb){
  var fileDetails = ctx.req.body;
  var files = [];
  var bucket = gcs.bucket(config.cloudStorage.for_download);

  async.eachSeries(fileDetails, function(fileDetail, eachFileCB){
    var fileName = "1999782_215_3_110669967104_Micth.doc";
    var remoteFile = bucket.file(fileName);
        var fileObj = {}; = fileDetail.fileName; = buffer;
  }, function(){
    console.log('ending the response.');
    cb(null, files);

In my Reactjs:

   var request = require('superagent');

    .post(api.BASE_URL + api.DOWNLOAD)
    .set('Cross-Domain', 'true')
    .set('Cache', 'false')
    .end(function(err, res) {
        if (res) {
            var fileData = res.body.files[0];
            //below works with text/plain
            var file = String.fromCharCode.apply(null, new Uint16Array(;
            var blob = new Blob([file], { type: 'application/msword' });
            var resURL = window.URL.createObjectURL(blob);
            var tempLink = document.createElement('a');
            tempLink.href = resURL;
        } else {
            console.log('Something went wrong. Err: ' + err);

I understand this has to do with the way data is being sent across the wire and how it is being put back in the browser. Any help is greatly appreciated.

About File open way

I tried to dynamic allocation at file name. But It doesn't work at all.

At my algorithm, Through char*,allocate file name, after that, using fopen function, make file.

Debugging stop after fopen function, said FP is NULL pointer... Even if input exact File route(like C:\programfiles), FP turned NULL Pointer.

Could you help me, why my algorithm is incorrect, and how could I use dynamic allocation at file name?

P.S Sorry, I'm not good at english. Next time, before post on stack-overflow, I'll study english.

char* ch;
FILE* fp;
int i = 1;

ch = (char*)malloc(sizeof(char));
    *ch= _getche();
    do {
        ch = (char*)realloc(ch, (i)* sizeof(char));
        *(ch + i - 1) = _getche();
        if (*(ch + i - 1) == '\b') {
            i -= 2; 


    }while(*(ch + i-1) != 13);
    *(ch + i-1) = 0;

    printf("\n%s\n", ch);
    fp = fopen(&ch, "w+");
    fwrite(ch, sizeof(char), i, fp);

Appending date and time to filename

I would like to know how to append the date and time to a filename in windows cygwin environment through command prompt.

Regards, Newbie_in

Java - adding file types to be recognized by Files.probeContentType(new File(".woff").toPath());

Java has a build in content types detector, however, it misses some filetypes naturally.

Files.probeContentType(new File(".woff").toPath());

It appears as if the implementation allows one to add more FileTypeDetectors but I cannot figure out how.


So how can one add more files to be probed?

On another note, do you consider Javas File.proveContentType to be effecient? Not only does one whas to create a Path object, but it also seems to iterate over these each time. I guess a caching mechanism would be required on top.

Android with DownloadManager get total file size

I have researched every where but no any solution. I have a snippet code that run and get the total file size normally while in debug mode of eclipse. But when i run the project the value of sizeOfDownloadingFile only return -1. Please help me, I compile with Android 22, thanks in advance.

 long id = downloadManager.enqueue(request);
            Cursor cursor = downloadManager.query(new DownloadManager.Query()
            if (!cursor.moveToFirst()) {
                Log.v("DownloadManagerService", "download list is empty");
            int sizeOfDownloadingFile = 0;
            sizeOfDownloadingFile = cursor.getInt(cursor
                    "File size of film " + mFilm.getmTitle() + " is "
                            + sizeOfDownloadingFile);

Byte output to binary file C++

I'm writing Huffman coding and everything was OK, until I tried to save the result into the archived file. Our teacher offered us to do it with such function (it takes each time a bit and after taking 8 of them should output a byte):

long buff=0;
int counter=0;
std::ofstream out("output", std::iostream::binary);

void putbit(bool b)
    if (b) buff++;
    if (counter>=8)


I tried an example with inputting sequence of bits like this:


but the output file in binary mode includes just: 1111111

As buff variable has the correct numbers (25 102 250 68 21 108) I suggested that I wrote the code in my notebook incorrectly and something is wrong with this line:


I tried to remove it with this line:

out << buff;

but got: 1111111111111111 Another way was:

out.write((char *) &buff, 8);

which gives:


It look like the closest to the correct answer, but still doesn't work correctly.

Maybe I don't understand something about file output.


Could you explain me how to make it work and why previous variants are wrong?

UPD: The input comes from this function:

void code(std::vector<bool> cur, std::vector<bool> sh, std::vector<bool>* codes, Node* r)
    if (r->l)
        if (r->l->symb)
            codes[(int)r->l->symb] = cur;

            for (int i=7; i>=0; i--)
                if ((int)r->l->symb & (1 << i))
                else putbit(0);
        code(cur, sh, codes, r->l);
    if (r->r)
        if (r->r->symb)
            codes[(int)r->r->symb] = cur;

            for (int i=7; i>=0; i--)
                if ((int)r->r->symb & (1 << i))
                else putbit(0);
        code(cur, sh, codes, r->r);

mardi 29 septembre 2015

Python File handling: standard input and output

import sys

fileobject=open('file.txt','w') fileobject.write(sys.stdin.readline()) Cat

Block quote

In the above code, shouldn't cat be in file after execution? However, when I run it, I find file empty. If my code is wrong, can someone explain how and sys.stdout.write() work and their uses?

reading only some strings from a file and storing it in stack in java

the file is:

The Lord Of the Rings
J.R.R. Tolkein
Great Expectations
Charles Dickens
Green Eggs and Ham
Dr. Seuss
Tom Sawyer
Mark Twain
Moby Dick
Herman Melville
The Three Musketeers
Alexander Dumas
The Hunger Games
Suzanne Collins
George Orwell
Gone With the Wind
Margret Mitchell
Life of Pi
Yann Martel

It has the title of the book in first line and in the next line it has author.

I only want to read first five books and authors from the file and then store it in a stack. Add the first two books with author in a stack and then remove the last one. How can I do it? This is what I did

Stack<Book> readingList = new Stack<>();

    File myFile = new File("books.txt");
    Scanner input = new Scanner(myFile);
    int i = 0;
    while (input.hasNext()) {
        readingList.push(new Book(input.nextLine(), input.nextLine()));
      System.out.println("Adding: " + readingList.lastElement().getInfo());
        readingList.push(new Book(input.nextLine(), input.nextLine()));
      System.out.println("Adding: " + readingList.lastElement().getInfo());
        System.out.println("Reading:  " + readingList.pop().getInfo());

Uploading digital products with size more than 5MB in nopCommerce results "Upload failed" erro

I have a shop for digital products that is built with nopCommerce (a famous eccommerce software). But uploading digital products with size more than 5MB results "Upload failed" erro, what is the solution?

why does "HTML file select" changes the order of selected files and sort them alphabetically?

I am trying to get the name of the files that are selected by a "file" input in HTML:

<input type="file" class="filestyle" name="file-select[]" id="file-select" accept="image/*" multiple>

I wrote this JavaScript code to do that:

$('#file-select').on("change", function(){
    var selectedFiless = this.files;
    for (var i = 0; i < selectedFiless.length; ++i) {
        var name = selectedFiless.item(i).name;

However, I noticed that the names are sorted in alphabetical order, not in selection order. for example, if I select z.jpg and then a.jpg, when I print the names, I have a.jpg, z.jpg (alphabetical order). but I want z.jpg, a.jpg (selection order).

download images to SD card with phonegap

Good evening, I am developing an application in phonegap and I need to download images on the SD card, but I get an error, I hope someone can help me, thanks

<a href="#" onclick="downloadImagess()">Download File</a>
 function downloadImagess(){
  alert("download just started.");
   var url = ''; 
var filename= 'Egipto';
    var ft = new FileTransfer();
       target_directory + filename, 
       function(entry) {
          alert("download complete!:"); //path of the downloaded file 
       function(error) {
          alert("download error" + error.code);
          //alert("download error" + JSON.stringify(error));
 catch (e){


Also left the image of the error

Python File Output, Looping, and Increasing

number = 1
name = 'Frames' + str(number) + '.html'
usedNumbers = []
if number in usedNumbers:
    number += 1

How would I go about doing this where 'number' increases by 1, puts out the html document, until it gets to 18, then stops before it gets to 19? ("Frames1.html. Frames2.html, ..., Frames18.html")

How do I modify the following code so that I'm actually reading in the contents of the file into an array then printing out the array? (C++)

The following code reads in a text file then prints it to the screen. It works perfectly however I want to first read in the contents into an array then print out the contents and I'm not sure how to do so.

#include <fstream> 
#include <iostream> 
#include <string>
using namespace std;

int main() 
string input; 

//Open file

std::ifstream inFile;"Input.txt");

while (true) 

//Get input

inFile >> input;

//Avoid repetition of last line:

if(inFile.eof() ) break;

//Print input on the screen

if (input == "a")
    std::cout << "Variable: " << input << "\n";

if (input == "=")
    std::cout << "Assignment: " << input << "\n";

if (input == "3")
    std::cout << "Integer: " << input << "\n";

if (input == ";")
    std::cout << "Semicolon: " << input << "\n";

if (input == "+")
    std::cout << "Operator: " << input << "\n";

if (input == "5")
    std::cout << "Integer: " << input << "\n";

if (input == "31")
    std::cout << "Integer: " << input << "\n";

if (input == "b")
    std::cout << "Variable: " << input << "\n";

if (input == "*")
    std::cout << "Operator: " << input << "\n";

if (input == "A")
    std::cout << "Variable: " << input << "\n";

if (input == "4")
    std::cout << "Integer: " << input << "\n";

if (input == "-")
    std::cout << "Operator: " << input << "\n";

if (input == "quit")
    std::cout << "Word: " << input << "\n";

//Close file

return 0;

End of program

Where to find public .dicom files online

I know there are libraries online where you can upload a .dicom file and view it from a computer but I need public access to a .dicom file that I can download to my computer.

File attributes slow

Using I download files using sftp then immediately set their attributes to normal.

    File.SetAttributes(Downloadedfile, Attr)  

where Attr is a FileAttribute. I later set the attributes to readonly

    File.SetAttributes(Downloadedfile, FileAttributes.ReadOnly) 

The problem I am having is that there appears to be a delay between the file being downloaded and the attributes being set by the OS(Win7). As a result the .normal attribute doesn't always get set but later the readonly attribute does. Is it possible to wait until the OS has finished whatever it is doing? I've looked around and seen various articles about changing the indexing and what the folder will be used to store but none of these suggestions has worked. Don't expect somebody to come up with "You need to this" but a pointer in the right direction would be a great help.

Select File from File-Manager via Intent

What I wanna do:

I wanna get the path as a String of a file, which I choose via an Android File Manager.

What I have:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Open with ..."), FILE_SELECT_CODE);

This code, works nearly fine for me, but there is one problem: I can only select my file with the following apps:

My Question:

Does anyone have a working code for choosing any file via the Android File Manager?

Python3: read from a file and sort the values

I have a txt file that contains data in the following fashion:


each value in a different file. I created three function:

the first one is to swap the values

def swap(lst,x,y):
    temp = lst[x]
    lst[x] = lst[y]
    lst[y] = temp

and the second function is to sort the values:

def selection_sort(lst):
    for x in range(0,len(lst)-1):
        swap(lst,x,findMinFrom(lst[x:])+ x)

the third function is to find the minimum value from the list:

def findMinFrom(lst):
    minIndex = -1
    for m in range(0,len(lst)):
        if minIndex == -1:
            minIndex = m
        elif lst[m] < lst[minIndex]:
            minIndex = m
    return minIndex

Now, how can I read from the file that contains the numbers and print them sorted?

Thanks in advance!

program to upload files to unix server via http

I have an Unix box which has only couple of http ports accessible outside the network. I have the ssh access to it inside the network and can install programs on it. Is there a program I can install to let me upload files to it via http. Thanks

How to read a file block-wise in python

I am bit stuck in reading a file block-wise, and facing difficulty in getting some selective data in each block :

Here is my file content :



    SEQUENCE=ai=0:at=221:ae=3:lu=100:lo=NNU:ei=1021055:lr=1: \
    USERID=ID=291821 NO_USERS=3 GROUP=ONE id_info=1021055 \
    CREATION_DATE=27-JUNE-2013 SN=1021055  KEY ="22WS \
    DE34 43RE ED54 GT65 HY67 AQ12 ES23 54CD 87BG 98VC \
    4325 BG56"

    SEQUENCE=ai=0:at=221:ae=3:lu=100:lo=NNU:ei=324356:lr=1: \
    USERID=ID=291821 NO_USERS=1 GROUP=ONE id_info=324356 \
    CREATION_DATE=27-MAY-2012 SN=324356  KEY ="22WS \
    DE34 43RE 342E WSEW T54R HY67 TFRT 4ER4 WE23 XS21 \
    CD32 12QW"

    SEQUENCE=ai=0:at=221:ae=3:lu=100:lo=NNU:ei=324356:lr=1: \
    USERID=ID=291821 NO_USERS=5 GROUP=ONE id_info=324356 \
    CREATION_DATE=27-MAY-2012 SN=324356  KEY ="22WS \
    DE34 43RE 342E WSEW T54R HY67 TFRT 4ER4 WE23 XS21 \
    CD32 12QW"


I am only interested in Block Name , NO_USERS, and id_info of each block . these three data to be saved to a data-structure(lets say dict), which is further stored in a list :

[{Name: IMPULSE ,NO_USER=3,id_info=1021055},{Name: PASSION ,NO_USER=1,id_info=324356}. . . ]

any other data structure which can hold the info would also be fine.

So far i have tried getting the block names by reading line by line :

fOpen = open('DATA.txt')
unique =[]
for row in fOpen:
    if "BLOCK" in row:
print unique

i am thinking of regular expression approach, but i have no idea where to start with. Any help would be appreciate.Meanwhile i am also trying , will update if i get something . Please help .

The order of fclose and free

Should we free memory before closing a file? For example, I open a file a, alloc an array b, then why should we free b before fclose(a)? What would happen if we do it otherwise?

connect to C drive to multiple remote PCs

I want to to connect to multiple (21 PCs to be exact) and put a file in the C drive, is there a way to do this?

I have researched around and it doesn't seem anyone has came up with a solution like this.

Crash when trying to open a file already in use, Visual Basic

The file will open fine when opened without editing it but once you edit the file and save it you can't open it again while in the same session.

Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
    If (ofdText.ShowDialog = DialogResult.OK) Then
        HCILtext.Text = ""
        HCILtext.Text = My.Computer.FileSystem.ReadAllText(ofdText.FileName, System.Text.Encoding.ASCII)
    End If
End Sub

Revit Custom File Properties

Hello I want to retrieve the custom properties of a file rfa or file rvt (Software Revit file format)

I could during my research came across this link:

but I have found no answer to the question.

Do you have an idea in advance thank you

Tomcat Webapp - getting resource by link

I hava an application which can upload files and stores them in the tomcat base folder(obtained by System.getProperty("catalina.base")...) How can I get this resource, picture for example by link? How to obtain absolute(or relative) path for those resources?

For example: http://localhost:8097/test.jpg

Http post format for image encoding(multipart/form-data)?

I'm now looking into the HTTP post format, and when I post a request with a file attachment, like an image, the post payload may look like the below:

Content-Disposition: form-data; name="nickname"

Content-Disposition: form-data; name="avatar"; filename="avatar.png"
Content-Type: image/png

????????!!!!!!!!<What's the format here?>


Now I just want to know that, if I curl a request in this way, what method should I use to pack the image?

I want to read an image file, and I can get the content stream, how can I manually construct such a HTTPRequest body as the payload?

Java app on tomcat server saving files on server instead of path

I currently have a application a Java web application on Tomcat 7 server that is supposed to generate files and save them on a path specified by the user. This works fine when i test it on my local machine but when i deploy to a dev server, the files get saved on the following path "conf/Catalina/localhost" on the server with the specified path as part of the name.

For instance, if i set the directory to where I want the file saved to "C:\Users\kbbj\Desktop", the files gets saved on the server as "C:\Users\kbbj\Desktop\filename.ext".

This is my code that creates a Word file (notice the last part where it saves):

public static void createWordDoc(Request request) throws Docx4JException {
        String filename ="_data_specs_v"+request.currentVersion+".docx";

        wordMLPackage = WordprocessingMLPackage.createPackage();

        //Create titles
        String title =" Data Specifications v."+request.currentVersion;
        String subtitle = request.analysis.analysisType+" Analysis for "+request.purpose.purpose;

        // Add titles to document

        //Create specification table
        wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Heading2", "Specifications");
        factory = Context.getWmlObjectFactory();

        Tbl table = factory.createTbl();
        Tr tableRow = factory.createTr();

        addStyledTableCell(tableRow, "Variable Name",true,null);
        addStyledTableCell(tableRow, "Values",true,null);
        addStyledTableCell(tableRow, "Method",true,null);
        addStyledTableCell(tableRow, "Analyst Instructions",true,null);

        System.out.println("Number of specs: "+request.specs.size());
        //Add specs to table
        for(Specification spec:request.specs){
            Tr newRow = factory.createTr();
            addTableCell(newRow,!=null ? : "");
            addTableCell(newRow, spec.variable.codeList!=null ? spec.variable.getCodeListAsString():"");
            addTableCell(newRow, spec.method!=null ? spec.method.method:"");
            addTableCell(newRow, spec.instructions!=null ? spec.instructions:"");


        //Save the file on project directory
        String filepath ="\\"+filename;
        System.out.println("file path: "+filepath);;

Any ideas of what is going on?
Help is appreciated!

File handler behavior in case there is no space left on Disk

There is a process running on our server, which writes well defined messages in a file. The process of writing is like one message per line and then next message in next line.

But we saw recently there were 2 message in a single line. During same time we saw that the disk space has got completely full at that time. But then later space was made available, the writing into file followed the expected pattern.

Can this double message in a single line could be because previous message was not completely dumped into file and when space was made available, writing started from last position till which write had been done previously ?

All I want to know is how any process writing into any file will behave in such cases. How does file handler meant to write behave in such scenarios ?

Need Shell script to monitor files on remote SUSE dir ApmPerfMonitor ApmPerfMonitor

We would need monitoring on below folder for respective directories & sub directories to see if the files in the directory are greater than 100 files. Also none of the file should sit more than 4 hrs.

If files in the directory is more than 100 we would need an alert.

Not sure why this script is working. Could you please confirm?

Path –


The Script:



if [ -f ${LOCKFILE} ]


exit 0


touch ${LOCKFILE}


/mftstaging/vim/inbound/active -ignore_readdir_race -depth -type f -m

min +60 -print | xargs wc -l`

if [[

${NUM:0:1} -ne 0 ]]; then

echo "${NUM:0:1} files older than 60minutes" | mail -s "batch import is

slow" ${MAILTO}


rm -rf ${LOCKFILE}

Spring, Java : Edit a file online and save it again on server.

I am working on a Spring-MVC application in which I am also working on attachments.

The situation is, when you click on Download attachment in the webapp, a browser shows two options, 1) Open with , 2) Download file.

What I am looking for is, if I open a .docx or .ppt or .txt or editable files, then they will be opened on client side.

But when the user edits the file, and clicks on save, then the file should also be updated on the server. Is there any way to provide such a mechanism? Thanks a lot.

My file-download code :

@RequestMapping(value = "/download/attachment/{attachid}/{groupaccountid}/{api}", method = RequestMethod.GET)
    public void getAttachmentFromDatabase(@PathVariable("attachid") int attachid, @PathVariable("groupaccountid") Long groupAccountId,
                                    @PathVariable("api") String api, HttpServletResponse response) {
            case "server":
                try {
                    GroupAttachments groupAttachments = this.groupAttachmentsService.getAttachmenById(attachid);
                    response.setHeader("Content-Disposition", "attachment; filename=\"" + groupAttachments.getFileName() + "\"");
                    FileCopyUtils.copy(groupAttachments.getSendAttachment(), response.getOutputStream());
                } catch (Exception ignored) {}

Thanks a lot.

python download(http) text file as binary. why? [on hold]

i'm trying to get some text files from the web using python. most of this have been downloaded correctly but few not. i've tested few solutions eg.wget,urllib.urlopen, urllib.urlretrive and some another. for example file from below urlpath : this file has been downloaded as a binary file, but this is simple ascii file. is there a solution to download all these files as ascii text files? or convert it to ascii ?

my code to do this :

  response = urllib.urlopen(url + filename)
    print "downloading " + url+filename
    with open(destDir+"/"+filename, "wb") as local_file:

How can I download files greater that 1MB from FTP using c#

I have created a C# application for downloading file from FTP. I could not download files having size greater than 1 MB. I got an error "Data is corrupted" while downloading the file. Here is my code for download.

int count = 0;
    byte[] buffer = new byte[1024];
    conn.ReadTimeout = 15000000;
    count = istream.Read(buffer, 0, buffer.Length);
    memoryStream.Write(buffer, 0, count);
} while (istream.CanRead && count > 0);

byteArray = memoryStream.ToArray();
var workBook = new XLWorkbook(memoryStream);
var workSheet = workBook.Worksheets.First()

Amr(NB) file format details

Please can anybody provide me a detailed information of the amr (nb) file format such as its headers, frame headers , meaning of each field in the header and their corresponding values as well as how to convert each samples of a frame into raw(pcm) samples programatically. I searched a lot on google but all in vain.There used to be a nokia developers wiki on amr format but it no longer exists. Please help me...

opening files on JAVA

import java.util.Formatter;
import java.util.Scanner;

public class JavaApplication3 {

   public static void main( String[] args ) throws Exception
      Formatter output = new Formatter( "clients.txt" ); // open the file
      Scanner input = new Scanner( ); // reads user input

      int accountNumber; // stores account number
      String firstName; // stores first name
      String lastName; // stores last name
      double balance; // stores account balance

      System.out.printf( "%s\n%s\n%s\n%s\n\n",
         "To terminate input, type the end-of-file indicator ",
         "when you are prompted to enter input.",
         "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
         "On Windows type <ctrl> z then press Enter" );

      System.out.printf( "%s\n%s", 
         "Enter account number (> 0), first name, last name and balance.",
         "? " );

      while ( input.hasNext() ) // loop until end-of-file indicator
         // retrieve data to be output
         accountNumber = input.nextInt(); // read account number
         firstName =; // read first name
         lastName =; // read last name
         balance = input.nextDouble(); // read balance

         if ( accountNumber > 0 )
            // write new record
            output.format( "%d %s %s %.2f\n", accountNumber, 
               firstName, lastName, balance );
         } // end if
               "Account number must be greater than 0." );
         } // end else

         System.out.printf( "%s %s\n%s", "Enter account number (>0),",
            "first name, last name and balance.", "? " );
      } // end while

      output.close(); // close file
   } // end main
} // end class CreateTextFile

but when go to file locetion and open the txt file thre is not any thing in there.i use windows and my problem is with endenging the file i think..please help me with how to write on a file in java.tnx

How to loop through a directory, get all file names, then get the contents of those files in Java

I am new here. Forgive me if I have any incorrect formatting.

So in C drive, I have a folder called "Search Files" and inside "Search Files", I have four subdirectories called "Folder 1", "Folder 2", "Folder 3", and "Folder 4".

Inside of "Folder 1", I have a text file called "hello.txt" and the contents of that file is "hello".

My expected output is "Directory of the file" + "file name" + "file body".

Below is the code that I have right now.

import java.util.Iterator;


public class FileDirectories {

    public static void main(String[] args) throws IOException {
        File[] files = new File("C:\\Search Files").listFiles();

    public static void showFiles(File[] files) throws IOException {
        String line = null;

                for (File file : files) {
                    if (file.isDirectory()) {
                        String fileName = "Directory" + file.getName();
                        //System.out.println("Directory: " + file.getName());
                        BufferedReader in = new BufferedReader(new FileReader(file));
                        while((line = in.readLine()) != null)
                        showFiles(file.listFiles()); // Calls same method again.
                    } else {
                        System.out.println("File: " + file.getName() + file.toString());
            }catch(NullPointerException e){

        /*Iterator<File> it = FileUtils.iterateFiles(new File("C://Search Files//"), null, false);
        while(it.hasNext()) {

When I execute the above code, I get the following error:

 Exception in thread "main" C:\Search   Files\Folder 1 (Access is denied)
        at Method)
        at org.raghav.stuff.FileDirectories.showFiles(
        at org.raghav.stuff.FileDirectories.main(

Once again, I need to get the file directory, the file name, and the contents of the file.

In case of the hello.txt, the expected output should be: C:\Search Files\Folder1\ hello.txt hello

Can you guys point me in the right directions? How to fix the above exception and how do I get a String that displays the directory, file name, and the contents of the file?

Thanks in advanced.

Get directoryname without full path (C unix)

DIR *dir;
struct dirent *entry;
if ((dir = opendir (argv[1])) != NULL) {
  while ((entry = readdir (dir)) != NULL) {
        printf ("%s\n", entry->d_name);
//recursive call, can post if needed

Im trying to make a program to find all files/folders with a specific name but with my current code I get the full filepath so I cant really use strcmp to find my path. Lets say that argv[2]=="Programs" then it wont find it if the path is "c://Programs". Is there any way in C to just get the name of the directory?

Php gives undefined index error while file upload

I searched internet and I could not find a solution for the problem. I have a form and when I submit only text fields there is no problem. But when I add file input and submit the form I get undefined index error.


    <form method="post" action="add.php" enctype="multipart/form-data">
        <input type="hidden" name="MAX_FILE_SIZE" value="10485760">
        <input type="text" name="topic" style="width:300px;" value="cars" />        
        <input type="file" name="file1" id="file1" />
        <input type="submit" name="submit" value="Add"/>


    // Form
else echo'NOOO';

This code always give NOOO when uploading file. I have controlled php.ini and upload is on.

how can i copy a resource file (named asd) to a path in C# Windows forms, with the easiest way?

how can i copy a resource file (named asd) to a path in C# Windows forms, with the easiest way? This isn't works:

File.Move(System.Text.Encoding.Default.GetString(Resources.asd), @"D:\asd");

please help me :)

How to get value from column in java

I am writing a file from shell script and reading that file from java and prints % in jsp page.. Here's the file :

0K .......... .......... .......... .......... ..........  0%    6.93 MB/s
   50K .......... .......... .......... .......... ..........  0%    1.75 MB/s
  100K .......... .......... .......... .......... ..........  0%    3.78 MB/s
  150K .......... .......... .......... .......... ..........  1%    1.93 MB/s
  200K .......... .......... .......... .......... ..........  1%    3.66 MB/s
  250K .......... .......... .......... .......... ..........  2%    7.84 MB/s
  300K .......... .......... .......... .......... ..........  2%    3.65 MB/s
  350K .......... .......... .......... .......... ..........  3%    2.45 MB/s

Here's the code to get pertucular value from file :

while((line = file.readLine()) != null) {

                    int li = line.lastIndexOf("%");
                    if(li > 0) 
                        progress = Integer.parseInt(line.substring(li - 3, li).trim());

Now the file format has been changed to below format :

% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0  164M    0     0    0     0      0      0 --:--:--  0:00:01 --:--:--     0
  0  164M    0  272k    0     0   117k      0  0:23:54  0:00:02  0:23:52  303k
  0  164M    0  624k    0     0   186k      0  0:15:04  0:00:03  0:15:01  322k
  0  164M    0  960k    0     0   221k      0  0:12:41  0:00:04  0:12:37  328k
  0  164M    0 1296k    0     0   242k      0  0:11:33  0:00:05  0:11:28  331k
  0  164M    0 1632k    0     0   258k      0  0:10:52  0:00:06  0:10:46  333k
  1  164M    1 1968k    0     0   267k      0  0:10:28  0:00:07  0:10:21  337k
  1  164M    1 2304k    0     0   276k      0  0:10:08  0:00:08  0:10:00  337k
  1  164M    1 2656k    0     0   283k      0  0:09:52  0:00:09  0:09:43  338k
  1  164M    1 2992k    0     0   289k      0  0:09:41  0:00:10  0:09:31  339k
  1  164M    1 3328k    0     0   293k      0  0:09:32  0:00:11  0:09:21  339k
  2  164M    2 3680k    0     0   297k      0  0:09:25  0:00:12  0:09:13  341k
  2  164M    2 4016k    0     0   300k      0  0:09:19  0:00:13  0:09:06  341k
  2  164M    2 4352k    0     0   303k      0  0:09:14  0:00:14  0:09:00  340k

Without changing much I just want to perform same operation (see code) to get the value of column 1 i.e : % value.

How to modify the above code or is there any method (like lastIndexOf) that will have the first's columns value???

How to store uploaded file into server path using either javascript or jquery

I want to know that how can I store my uploaded file from my local system into one server path like('/newfolder/tests/') using either javascript or jquery, so that I can grab it from that path and can display it on my view page. Please provide me any solution for it as I'm new to this Files system. Thanks in advance.

How to download a file to the server with PHP?

I want the user to give the PHP script an URL of a file (which I already did), but then I want the PHP script to take that URL, download the file in the URL, and save it on the server. I've been searching for this but haven't found a soultion.

Is it possible, and if so, how? Thanks.

Can we pass mht file as an input parameter in xml file?

i am currently doing a mail integration utility where i need to download the mail body and attachments. and pass the attachments as input in another xml file. so can i pass the mht file in xml code? and what are the pros and cons in it?

Kindly help me out guys,

Thanks in advance,

Sivaramakrishnan R

How can I read the lines which between the "start" and "end" flags from a file by using python

For example, the content of the file is like this:

this is the first line;
this is the second line;
this is the third line;
this is the forth line;
this is the fifth line;
this is the sixth line;
this is the seventh line;

"start" and "end" is the flag,i want print the lines which is between the two flags.The result what i want to is like this:

this is the second line;
this is the third line;
this is the forth line;
this is the fifth line;

So, how can i process this file.Thanks for your help.

dealing with long file paths

I am taking over a web project and have not spoken with the former developer yet. I am using Windows 7. When I am trying to copy the files of the website to my machine locally, FTP tells me there are a bunch of files I can't copy to my local disk due to long file paths, like such:


Only subfolders of


seem to be an issue and they appearently all are related to grunt somehow. I want to make a complete backup of the page. I haven't worked with grunt before but I might want to start working with it. I don't know why those paths are so long and if I can change them or neglect those files. I will speak with the developer soon.

But maybe someone can help me right now... Any suggestions?

lundi 28 septembre 2015

Where are FIle.ReadAll***Async/WriterAll***Async/AppendAll***Async methods?

There are bunch of rather convenient methods in File class, like ReadAll***/WriteAll***/AppendAll***.

I'm faced with a number of cases, when I need their asynchronous counterparts, but they just don't exist.

Why? Are there any pitfalls?
I know, that these methods could be easily implemented, but is there any reason to not implement them in framework out-of-the-box?

linux command "tail -f filename" doesnt work

I use 'tail -f filename' monitoring a text file,and use vi editor adding a line at the end of the file.

But after saving the file I did not see the update on the terminal which 'tail -f' are monitoring.

What is the problem? is vi editor has buffer or something?

C++ : Reading file and store data in multi-vector

I am trying to read data file with the this format

T1: I1,I2,I5 
T2: I2,I4 
T3: I2,I3 
T4: I1,I2,I4 
T5: I1,I3 
T6: I2,I3 
T7: I1,I3 
T8: I1,I2,I3,I5 
T9: I1,I2,I3 

I don't want to read the first column T1,T2,T3 ...... , but each line will be a dataset I want to start read after (space ' ' ) and end with each line and how can I separate the data according to (comma ',')

I wrote this code but it didn't work correctly and it reads the first column anyway

string CItem;

// set of elements
set< CItem > CItemSet;

 CItemSet CTransaction;

// set of transactions
vector< CTransaction > CTransactionSet;

ifstream inFile(inFileName);
    if (!inFile)
        cout << "Failed to open input file filename:." << inFileName;

CTransactionSet transSet;
    CTransaction tran;
    string txtLine;
    // read every line from the stream
    while (getline(inFile, txtLine))

        istringstream txtStream(txtLine);
        string txtElement;
        // read every element from the line that is seperated by commas
        // and put it into the vector or strings

        while (getline(txtStream, txtElement, ','))
            if (txtElement == ": ") break;
            else tran.insert(txtElement);

linux socket programming: Socket writing line to a file in c

Hi Guys I am having trouble trying to write to file. I am in networking class and we are supposed to implement a simple ftp server. It involves reading a file and sending it over the socket to a client. When it reaches the client then you write the output to a file. I have implemented a server and client and they both work fine when printed. However when I append to the file it works differently. The output comes out different. Instead of writing all the lines as before now only the first line is is being written to file or sometimes two lines.I don't know what is causing the problem. Here is the code. I pass buffer of size 4096.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

#include <sys/wait.h>
#include <sys/types.h>
#include <sys/socket.h>

#define MAX_LENGTH 4096

int write_line(char string[MAX_LENGTH]){
    FILE *fp;

    char* array = strdup(string);
    char* filename="client.txt";
    char* dir=get_current_dir_name();

    char fullpath[MAX_LENGTH];

    strcat(fullpath, dir);
    strcat(fullpath, "/");
    strcat(fullpath, filename);

    fp=fopen(fullpath, "a");

        return -1 ; 

    int i;

    for (i=0; i<strlen(string); i++)

    bzero(fullpath, MAX_LENGTH);

    return 0;

c++ Writing a structure in a file

i cant write correctly a structure into a file, my structure and code is this struct Registro { long int Numero; string Dia; //DDMMAAAA int HoraEntrada; string SalidaHHMM; }; FILE* archivo = fopen(nombrefinal,"wb"); fwrite(&empleado,sizeof(Registro),1,archivo); fclose(archivo);

my problem is the ouptut, it throws me this into the file a80d 6200 7412 6200 e40d 6200 6b04 0000 and i tried everything, please help me.

Using and FileINputStream to download a File from a database

I have a method to record data in a database that icnludes a BLOB field, I am using

 File destFile= new File(fichero.getFileName());
 FileUtils.copyInputStreamToFile(fichero.getInputstream(), destFile);

The above code works perfectly, now I am looking for a way to do the Oposite, I mean, from an Object that has the property "File" that I got from the database, convert it so it can be downloaded

In a form, I just put a command link that passes the file.file to a backing bean method.

The following method works fine, the BLOB is retrieved and copied to the path /home/user/files

But, the browser does not download it, what I want to do is that when the user clicks on the commandlink the method just download the file as usual (prompting the user as any normal download)

 public FileOutputStream getFichero (File file) throws FileNotFoundException, IOException {

       FileInputStream in = new FileInputStream (file);
       FileOutputStream out = new FileOutputStream("/home/user/files/"+file.getName());
       int c;

       while ((c = != -1) {

       return out;