【发布时间】:2013-02-01 13:25:45
【问题描述】:
我正在尝试向这篇文章提出类似的问题: C: read binary file to memory, alter buffer, write buffer to file 但答案对我没有帮助(我是 C++ 新手,所以我无法理解所有内容)
如何循环访问内存中的数据,并逐行遍历,以便将其写入不同格式的文件?
这就是我所拥有的:
#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 zng 392
其中第一个元素是字符,其余项可以是数字或字符。我正在尝试将其读入内存,因为逐行循环比读取一行、处理然后写入要快得多。我在 64 位 linux 上编译。让我知道是否需要进一步澄清。再次谢谢你。
编辑 2 我正在使用 switch 语句来处理每一行,其中每行的第一个字符决定了如何格式化该行的其余部分。例如“M”表示毫秒,我将接下来的三个数字放入一个结构中。每行都有一个不同的第一个字符,我需要为此做一些不同的事情。
【问题讨论】:
-
这是 C++ 和 C 的大混合。
-
可以像访问数组一样访问指针。如果你想逐行访问,你应该查看
std::istringstream。 -
我第一次看到
cout和malloc在同一个函数中。 -
删除
sizeof(char)。对象的大小定义为 char 大小的倍数,因此sizeof (char)定义为 1。 -
当你做运行它时,究竟会发生什么?