2014-11-24 137 views
-3

因此,我正在编写一个函数来读取文件并将其内容放入另一个文件中。这是我迄今为止所得到的:读取文件并将其内容写入另一个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"); 
    exit(o); 
} 
while(file >> word) { 
    cout<< word << '\n'; 
} 
file.close(); 

} 

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

+4

为什么不使用你的平台的复制文件的功能? – cdhowie 2014-11-24 23:37:21

+2

这是如何回答这个问题的? – dwvaxaz 2014-11-24 23:41:08

+0

我不记得'std :: ofstream(output)<< std :: ifstream(input).rdbuf())'现在是否有效,或者它仍然是两行或三行。可能是单独的行。 – 2014-11-24 23:43:53

回答

6

你不需要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)); 
} 
+0

请注意,如果'argv [1]'或'argv [2]'不存在有效名称,那么这是未定义的行为。 – 0x499602D2 2014-11-25 00:35:45

+0

当我直接与流缓冲区打交道时,我不确定'binary'是否必要,但它不会受到伤害。 – 2014-11-25 17:18:34

2

,而不是一个单词词巴西斯,不与空格工作WEEL这样做,你可以(如果你真的啥子用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(); 

不过它将使更多的SENS使用您的操作系统functionnality的转储

相关问题