[英]C++ How to write block of strings to file?
我有兩個非常大的數字(每個最多23位數),我想盡可能快地將它們打印到文件中。 文件中的行應如下所示:
number1 [space] number2 [\\ n]例如。 123456789999999 99999965454644
我的方法是將行收集到一個大緩沖區中,當緩沖區已滿時,使用fwrite()將其寫入文件。
最大的問題是,我不知道如何從這兩個數字創建一個字符串並將它們保存到一個字符串/ char數組中。 正如我所提到的,字符串的長度是可變的,它只能是3個字符甚至50個字符。
const int OUT_BUFFER_SIZE = 65536;
string out_buffer[OUT_BUFFER_SIZE];
int out_size = 0;
FILE* output_file = fopen("result.out", "w");
void print_numbers(FILE* f, long long num1, long long num2)
{
const int ELEMENT_SIZE = 50;
char line[ELEMENT_SIZE];
sprintf(line, "%lld %lld\n", num1, num2);
out_buffer[out_size] = line;
out_size++;
if (out_size == OUT_BUFFER_SIZE)
{
fwrite(out_buffer, ELEMENT_SIZE, OUT_BUFFER_SIZE, f);
}
}
fclose(output_file);
有沒有其他方法可以解決這個問題? 謝謝。
編輯1:我嘗試了兩種附加方法:
1)使用fprintf(f, "%lld %lld\\n", num1, num2);
立即將數字寫入文件fprintf(f, "%lld %lld\\n", num1, num2);
2)使用ofstream與@somnium提到的完全相同。
我確實測量了它們,令人驚訝的是,1)方法比第二種方法快2倍。
如果您使用的是C ++而不是普通的C,則可以使用:
#include <iostream>
#include <fstream>
using namespace std;
void print_numbers(const std::string fname, long long num1, long long num2)
ofstream myfile;
myfile.open (fname);
myfile << num1 << " " << num2 << '\n';
myfile.close();
return 0;
}
這已經成為必要的緩沖基礎。
使用“fprintf(f,”%lld%lld \\ n“,num1,num2)有什么問題;”? fprintf使用緩沖IO,因此添加另一層緩沖是沒有意義的。 如果要增加緩沖區大小,可以使用setvbuf()。
但是,最快的方法可能是避免任何緩沖並將所有數據傳遞給writev(),這需要用一個系統調用寫入一組緩沖區。 但是,處理部分寫入(允許writev執行)並非易事。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.