2014-11-24 132 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的轉儲

相關問題