C++ Reading file backwards from the end of the file

前端 未结 3 1155
旧时难觅i
旧时难觅i 2021-01-06 03:44

I am trying to write a program with a menu that reads from a text file a few different ways. I\'m just working on menu option #2 still (reading backwards from the end of the

3条回答
  •  旧时难觅i
    2021-01-06 04:13

    The following is my solution to the question. When open the file, I use ios::ate to set the file position to the end of the file and use seekg method to read back. I am not sure whether there is a more efficient way to solve this question.

    void readFile(char *fileName){
        char c;
        std::ifstream myFile(fileName,std::ios::ate);
        std::streampos size = myFile.tellg();
        for(int i=1;i<=size;i++){
            myFile.seekg(-i,std::ios::end);
            myFile.get(c);
            printf("%c\n",c);
        }
    }
    

提交回复
热议问题