Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/160.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++中的文件反转_C++_File_Copy - Fatal编程技术网

C++中的文件反转

C++中的文件反转,c++,file,copy,C++,File,Copy,我用这段代码逐字读取文件并将其复制到另一个文件中。我需要把文件倒过来。因此,每次复制字符时,我都试图将文件指针设置为起始位置 using namespace std; int main () { fstream myfile,infile; char c; infile.open("inputfile", ios::in); myfile.open ("outputfile",ios::out|ios::trunc); while(infile.get(c)) {

我用这段代码逐字读取文件并将其复制到另一个文件中。我需要把文件倒过来。因此,每次复制字符时,我都试图将文件指针设置为起始位置

using namespace std;

int main () {
  fstream myfile,infile;
  char c;
  infile.open("inputfile", ios::in);
  myfile.open ("outputfile",ios::out|ios::trunc);
  while(infile.get(c))
  {
      myfile<<c;
      myfile.seekp(0,myfile.beg);
  }
  infile.close();
  myfile.close();
  return 0;
}

但是输出文件只有我要复制的第一个字符。如何解决此问题。

只要文件不太大,就可以将其存储在向量中,然后将其写入outputfile:

#include <fstream>
#include <iostream>
#include <vector>
using namespace std;

int main () {
  fstream myfile,infile;
  char c;
  vector<char> contentVector;
  infile.open("inputfile", ios::in);
  myfile.open ("outputfile",ios::out);
  while(infile.get(c)) {
    contentVector.push_back(c);
  }
  for (int i = contentVector.size() - 2; i >= 0; --i) {
    myfile << contentVector[i];
  }
  myfile << '\n';
  infile.close();
  myfile.close();
  return 0;
}
如果inputfile的大小合理,则可以使用

// open inputfile
ifstream in("inputfile");
// read it to vector
vector<char> v( (std::istreambuf_iterator<char>(in)),
                std::istreambuf_iterator<char>() );
// create outputfile
ofstream out("outputfile");
// copy reversed vector to outputfile
copy(v.rbegin(), v.rend(), ostreambuf_iterator<char>(out));

如果inputfile的大小可以是数百个MIB,那么您应该使用ifstream::seekg和ifstream::read方法写入缓冲I/O。

文件没有神奇的插入模式。通过将位置重置为文件的开头,您只会一次又一次地覆盖第一个字符。您将不得不反向流式传输文件内容。是要逐字符还是逐行反向?通过使用ios::out | ios::trunc,您每次都会覆盖写入文件的内容。