0

I read the name of a file from input and i want to sort the content and the sorted content must be added in file. But i get only this output:

Start End

function main(){
    global $argc, $argv;
    if($argc == 1){
        print("Please provide text file path");
        return;
    }
    print("START\n");
    run($argv[1]);
    print("END\n");
}

function run($file_name){
    $br = fopen($file_name,"r");
    $bw = fopen($file_name,"a");
    if($br && $bw){
        while(($line = fgets($br))!==false){
            if($line == "\n" || $line == "") break;
            $values = preg_split('/\s+/', $line);
            $res = array();
            for($i=0; $i< count($values)-1;$i++){
                $res[]=(int)$values[$i];
            }
            fwrite($bw,to_string(insert($res))."\n");
        }
    }
    fclose($br);
    fclose($bw);
}

"Insert" is the insertion sort function: fwrite($bw,to_string(insert($res))."\n"); that i call.

MCMXCII
  • 1,043
  • 4
  • 13
  • 26
  • 1
    What output did you expect? You're not printing anything more than `START` and `END`. – ccKep Apr 19 '18 at 11:24
  • I can not add the name of file that can be sorted. It appears only Start and End. – user9669439 Apr 19 '18 at 12:02
  • Indentation would greatly help read your code. Ex. https://hotexamples.com/examples/-/Indentation/-/php-indentation-class-examples.html My brain goes numb after 5 lines of this. – Nic3500 Apr 19 '18 at 12:06
  • Sorry, now looks better. – user9669439 Apr 19 '18 at 12:09
  • Yes, indeed, much better! You could read the file into an array (http://php.net/manual/en/function.file.php), sort the array (http://php.net/manual/en/function.sort.php), write the result to file (http://php.net/manual/en/function.file-put-contents.php) after flattening your array into a string (https://stackoverflow.com/questions/7490488/array-to-string-php). – Nic3500 Apr 19 '18 at 12:12
  • The only problem I see in your code is that you open the same file twice. Once for read (makes sense), and once for append (makes less sense). You should read from $file_name, write to a temporary file and rename the temporary file to $file_name when done. – Nic3500 Apr 19 '18 at 12:14
  • *I can not add the name of file that can be sorted. It appears only Start and End* - Your code expects the filename to be in `$argv[1]` - which is the first argument to the script (eg. `foo.php myFile.txt`) – ccKep Apr 19 '18 at 12:41

0 Answers0