2013-08-05 79 views
0

我正在嘗試編寫一個程序,在該程序中我已經讀取和寫入已經創建的csv文件。其中一些被新數據覆蓋,而另一些則被簡單地添加到文件的末尾。我打開使用的文件:覆蓋與添加到C++中讀取csv文件的結尾

ifstream file; 
file.open("") 

然後我讀取文件並做必要的計算。我只是不知道如何以我需要的兩種方式回寫這個文件。我相對比較新的編程,所以最簡單的答案是最好的。

+0

請記住,如果覆蓋現有數據,新數據可能需要具有完全相同的大小。 –

+0

是不是打開它並在追加模式下打開它有區別?不是一種模式只是取代以前的文件中的什麼? – user2611318

+0

如果您覆蓋整個文件,那麼應該沒有問題,但是如果您在中間覆蓋數據,則需要確保新數據的大小相同(或者如果較小,則可能使用空格填充) –

回答

0

我能想到這兩個方便的功能。

你可能想要typedef某些類型。

/*Read CSV using a vector of vector of string */ 
std::vector<std::vector<std::string> > loadCSV(std::istream &input){ 
    std::string csvLine; 
    std::vector<std::vector<std::string> > data; 

    while(std::getline(input, csvLine)){ 
    std::istringstream csvStream(csvLine); 
    std::vector<std::string> csvRow; 
    std::string csvCol; 

    while(std::getline(csvStream, csvCol, ',')) 
     csvRow.push_back(csvCol); 
    data.push_back(csvRow); 
    } 
    return data; 
} 

/*Modify Data by accessing elements of data[row][col]*/ 
/*Add new data using push_back ref. loadCsv function */ 

/* Finally update */ 
void saveCSV(std::ostream &output,const std::vector<std::vector<std::string> >& data){ 
    if(!data.size()) 
    return; 
    std::vector<std::vector<std::string> >::const_iterator i=data.begin(); 
    for(; i != data.end(); ++i){ 
    std::vector<std::string> row =*i; 
     if(!row.size()) 
      continue; 
    std::vector<std::string>::const_iterator j=row.begin(); 
    output<<*(j++); 
    for(;i != row.end();++j) 
     output<<','<<*j; 
    output<<std::endl; 
    } 
}