Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/9.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++ - Fatal编程技术网

读取文件并将其内容写入另一个C++

读取文件并将其内容写入另一个C++,c++,C++,因此,我正在编写一个函数来读取一个文件并将其内容放入另一个文件中。以下是到目前为止我得到的信息: void myFile::printWords(string input, string output) { ifstream file(input.c_str()); ofstream file_out(output.c_str()); string word; if(!file.is_open()) { printf("File can't be opened\n"); ex

因此,我正在编写一个函数来读取一个文件并将其内容放入另一个文件中。以下是到目前为止我得到的信息:

void myFile::printWords(string input, string output) {
 ifstream file(input.c_str());
 ofstream file_out(output.c_str());
 string word;

 if(!file.is_open())
 {
  printf("File can't be opened\n");
  exit(o);
 }
 while(file >> word) {
  cout<< word << '\n';
 }
 file.close();

}

问题是如何继续写入文件?

复制文件并不需要iostreams;您只需要原始流缓冲区。例如,这里有一个完整的复制程序:

#include <algorithm>   // for std::copy
#include <cstdlib>     // for EXIT_FAILURE
#include <fstream>     // for std::filebuf
#include <iterator>    // for std::{i,o}streambuf_iterator

int main(int argc, char *argv[])
{
    if (argc != 3) { return EXIT_FAILURE; }

    std::filebuf infile, outfile;
    infile.open(argv[1], std::ios::in | std::ios::binary);
    outfile.open(argv[2], std::ios::out | std::ios::binary);

    std::copy(std::istreambuf_iterator<char>(&infile), {},
              std::ostreambuf_iterator<char>(&outfile));
}

<>而不是在Word到BASIS上做这件事,它不与白空间一起工作,如果你真的想使用C++,就可以使用文件

的char []转储。
std::fstream ifile(input.c_str(), std::ios::in | std::ios::binary | std::ios::ate);
std::fstream ofile(output.c_str(), std::ios::out | std::ios::binary);

if (!(ifile.is_open() && ofile.is_open())) { handle_error(); }

size_t size   = ifile.tellg();
char*  buffer = new char[size];

ifile.seekg(0, std::ios::beg);
ifile.read(buffer, size);
ofile.write(buffer, size);

ifile.close();
ofile.close();

尽管如此,使用操作系统功能还是更有意义的

为什么不使用平台的复制文件功能?这如何回答这个问题?我想不起来std是否:ofstreamoutput@dwvaxaz这不是故意的,这是评论,不是回答@dwvaxaz因为读取文件并将其内容写入另一个文件正是复制文件的定义,不是吗?请注意,如果argv[1]或argv[2]作为有效名称不存在,则这是未定义的行为。我不确定在直接处理streambuffer时是否需要二进制文件,但这不会造成伤害。