C++: Everytime I read in by fstream I got 1 extra character at the end

前端 未结 2 504
被撕碎了的回忆
被撕碎了的回忆 2021-02-08 20:52

Everytime I read in by fstream I got 1 extra character at the end, How can I avoid this?

EDIT:

ifstream readfile(inputFile);
ofstream writefile(outputFil         


        
相关标签:
2条回答
  • 2021-02-08 21:26

    This typically results from testing for the end of file incorrectly. You normally want to do something like:

    while (infile>>variable) ...
    

    or:

    while (std::getline(infile, whatever)) ...
    

    but NOT:

    while (infile.good()) ...
    

    or:

    while (!infile.eof()) ...
    

    Edit: The first two do a read, check whether it failed, and if so exit the loop. The latter two attempt a read, process what was "read", and then exit the loop on the next iteration if the previous attempt failed.

    Edit2: to copy one file to another easily, consider using something like this:

    // open the files:
    ifstream readfile(inputFile);
    ofstream writefile(outputFile);
    
    // do the copy:
    writefile << readfile.rdbuf();
    
    0 讨论(0)
  • 2021-02-08 21:33

    Based on the code, it appears what you're trying to do is copy the contents of one file to another?

    If so, I'd try something like this:

    ifstream fin(inputFile, ios::binary);
    
    fin.seekg(0, ios::end);
    long fileSize = fin.tellg();
    fin.seekg(0, ios::beg);
    
    char *pBuff = new char[fileSize];
    fin.read(pBuff, fileSize);
    fin.close();
    
    ofstream fout(outputFile, ios::binary)
    fout.write(pBuff, fileSize);
    fout.close;
    delete [] pBuff;
    
    0 讨论(0)
提交回复
热议问题