我試圖問一個類似的問題,這個帖子: C: read binary file to memory, alter buffer, write buffer to file 但答案沒有幫助我(我是新來的C++,所以我不能」 t瞭解全部)讀文件到內存中,通過數據環路,然後寫入文件
我該如何讓循環訪問內存中的數據,並逐行瀏覽,以便我可以將它寫入不同格式的文件?
這是我有:
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
using namespace std;
int main()
{
char* buffer;
char linearray[250];
int lineposition;
double filesize;
string linedata;
string a;
//obtain the file
FILE *inputfile;
inputfile = fopen("S050508-v3.txt", "r");
//find the filesize
fseek(inputfile, 0, SEEK_END);
filesize = ftell(inputfile);
rewind(inputfile);
//load the file into memory
buffer = (char*) malloc (sizeof(char)*filesize); //allocate mem
fread (buffer,filesize,1,inputfile); //read the file to the memory
fclose(inputfile);
//Check to see if file is correct in Memory
cout.write(buffer,filesize);
free(buffer);
}
我明白任何幫助!
編輯(在數據更多信息):
我的數據是5和10GB之間變化不同的文件。有大約3億行數據。每一行類似
M359
T359 3520 359
M400
A3592名義零增長392
其中第一個元素是一個字符,其餘的項目可以是數字或字符。我試圖將它讀入內存中,因爲逐行循環會比讀取一行,處理然後寫入要快得多。我正在編譯64bit linux。如果我需要進一步澄清,請告訴我。再次謝謝你。
編輯2 我使用的switch語句來處理每一行,每一行的第一個字符確定如何將線路的其餘部分進行格式化。例如'M'表示毫秒,並且我將接下來的三個數字放到一個結構中。每行都有不同的第一個字符,我需要做一些不同的事情。
這是C的大混合++和C. – 2013-02-16 18:53:59
可以像訪問數組一樣訪問指針。如果你想逐行訪問,你應該看看['std :: istringstream'](http://en.cppreference.com/w/cpp/io/basic_istringstream)。 – 2013-02-16 18:56:53
第一次我看到'cout'和'malloc'在同一個函數中。 – us2012 2013-02-16 19:02:12