Search code examples
c++makefilediffexecute

problem with opening the input file with diff script (in c++)


On my assignment , I'm asked to compare the output text file with diff .

my code can't open the input file when I use operator < (last line of diff script).

how should I declare the inputfile in main? what does the last line in script.sh file do ?

script.sh file:

unzip A4-"$1".zip
(cd A4-"$1"/; make)
cp A4-"$1"/Scheduler.out .
echo "##### DIFF #####"
./Scheduler.out < sample.in | diff sample.out -

int main (int argc , char* argv[]){
    fstream inputFile (argv[1],fstream::in);
    fstream outputFile ("outputFile.out",fstream::out);
    /*...*/
}

Solution

  • One common pattern for commands is to either read from a file supplied as an argument, or, when an argument is missing, read from std::cin. Another common practise for commands in many environments is to accept - as an indicator that you want to read from std::cin. It could be implemented like this:

    #include <iostream>
    #include <fstream>
    #include <vector>
    
    int streamer(std::istream& is) {
        std::ofstream out("outputFile.out");
        if(out) {
            /*...*/
            return 0; // if all's well
        } else
            return 1; // open failed
    }
    
    int cppmain(const std::vector<std::string>& args) {         
        if(args.size() && args[0] != "-") { // or do something cleaver to read from all "args".
            std::ifstream is(args[0]);
            if(is)
                return streamer(is);   // read from a file
            else
                return 1;              // open failed
        } else {
            return streamer(std::cin); // read from stdin
        }
    }
    
    int main(int argc, char* argv[]) {
        return cppmain({argv + 1, argv + argc});
    }
    

    Remove the && args[0] != "-" part if you get in an argument with someone who likes naming files -. I put it there just to show the option.

    The last line:

    ./Scheduler.out < sample.in | diff sample.out -
    

    Broken down:

    ./Scheduler.out < sample.in

    The shell opens sample.in for reading and executes ./Scheduler.out. std::in in .\Schduler.out, that is usually connected to a terminal, is replaced by the open sample.in handle.

    ... | diff sample.out -

    std::cout from the command ... replaces std::cin in diff by the shell. The - is an argument that is interpreted by diff and means that it will diff one file with the input it gets from std::cin, much like what I did in cppmain in my example.