天天看点

C++ CSV解析

/*
 * FileUtil.h
 *
 *  Created on: 2013-7-1
 *      Author: frodo
 */

#ifndef FILEUTIL_H_
#define FILEUTIL_H_

#include <vector>
#include <stdio.h>

class TableRowEvent{
public:
	virtual void onReadRow(int tag, int count, char** cols, int row)  = 0;
};

class FileUtil {
public:
	FileUtil(){ };
	virtual ~FileUtil(){  };
public:
	static bool readResource(int tag, const char* filename, TableRowEvent* event);
};

#endif /* FILEUTIL_H_ */           
/*
 * FileUtil.cpp
 *
 *  Created on: 2013-7-1
 *      Author: frodo
 */

#include "FileUtil.h"
#include <string.h>


void prcessRow(int tag, char* data, size_t dataLen, int row, TableRowEvent* event){

	if(dataLen == 1 && *data == '\r') {
		return;
	}
	int cur = 0;
	int titleCount = 0;

	char* titleBuffer[256];
	for(int i = 0 ; i < 64 ; i++){
		titleBuffer[i] = new char[256];
		memset(titleBuffer[i], 0, 256);
	}

	for(unsigned int i = 0 ; i < dataLen ; i++){
		char title[256];
		cur = 0;
		memset(title, 0 , sizeof(title));
		while(data[i] != '\t' && i < dataLen){
			title[cur] = data[i];
			cur++;
			i++;
		}
		title[cur] = '\0';
		memcpy(titleBuffer[titleCount], title, cur);

		titleCount++;

	}


	if(event){
		event->onReadRow(tag, titleCount, titleBuffer, row);

	}

}

bool
FileUtil::readResource(int tag, const char* filename, TableRowEvent* event){

	FILE* pFile = fopen(filename, "rb");
	if(!pFile) return false;
	int _irow = 0;
	char cur = 0;
	unsigned long _pfindex = 0;
	char rows[1024];
	memset(rows, 0 , sizeof(rows));



	while(fread(&cur, 1,1, pFile) > 0){
		if(cur == '\n'){
			prcessRow(tag, rows, _pfindex, _irow, event);
			memset(rows, 0 , sizeof(rows));
			_pfindex = 0;
			_irow++;
			continue;
		}
		rows[_pfindex] = cur;
		_pfindex++;

	}
	fclose(pFile);

	return true;

}
           

继续阅读