How do you get a file in C++?

后端 未结 4 1884
既然无缘
既然无缘 2021-01-22 03:53

So the teacher has posed this assignment:

You have been hired by the United Network Command for Law Enforcement, and you have been given files containing null cyphers yo

4条回答
  •  醉酒成梦
    2021-01-22 04:04

    [EDIT] include support for command line arguments [EDIT] Fixed possible memory leak [EDIT] Fixed a missing reference

    #include 
    #include 
    
    using namespace std;
    
    int main(int argc, char *argv){
        ifstream infh;  // our file stream
        char *buffer;
    
        for(int c = 1; c < argc; c++){
            infh.open(argv[c]);
    
            //Error out if the file is not open
            if(!infh){
                cerr << "Could not open file: "<< argv[c] << endl;
                continue;
            }
    
            //Get the length of the file 
            infh.seekg(0, ios::end);
            int length = infh.tellg();
    
            //reset the file pointer to the beginning
            is.seekg(0, ios::beg);
    
            //Create our buffer
            buffer = new char[length];
    
            // Read the entire file into the buffer
            infd.read(buffer, length);
    
            //Cycle through the buffer, outputting every other char
            for(int i=0; i < length; i+= 2){
                cout << buffer[i]; 
            }
            infh.close();
        }
        //Clean up
        delete[] buffer;
        return 0;
    }
    

    Should do the trick. If the file is extremely large, you probably shouldn't load the entire file into the buffer.

提交回复
热议问题