如何在C++中读取.dat文件
问题描述:
如何在C++中编写代码读取.dat文件,这些文件包含文本数据(数字和用分隔符组织的字符)。是fstream标准库的最佳选择?我们如何定义文件路径。第二个问题是,如果我想读这些文件并将它们加载到SQL Server数据库中,它会是不同的机制?如何在C++中读取.dat文件
答
是的,你可以使用fstream来做到这一点。
以下是一些代码,您可以使用 将数据拆分成由分隔符分隔的数组。只需将 DELIMITER更改为您的分隔符。
#include <iostream>
using std::cout;
using std::endl;
#include <fstream>
using std::ifstream;
#include <cstring>
const int MAX_CHARS_PER_LINE = 512;
const int MAX_TOKENS_PER_LINE = 20;
const char* const DELIMITER = " ";
int main()
{
// create a file-reading object
ifstream fin;
fin.open("data.txt"); // open a file
if (!fin.good())
return 1; // exit if file not found
// read each line of the file
while (!fin.eof())
{
// read an entire line into memory
char buf[MAX_CHARS_PER_LINE];
fin.getline(buf, MAX_CHARS_PER_LINE);
// parse the line into blank-delimited tokens
int n = 0; // a for-loop index
// array to store memory addresses of the tokens in buf
const char* token[MAX_TOKENS_PER_LINE] = {}; // initialize to 0
// parse the line
token[0] = strtok(buf, DELIMITER); // first token
if (token[0]) // zero if line is blank
{
for (n = 1; n < MAX_TOKENS_PER_LINE; n++)
{
token[n] = strtok(0, DELIMITER); // subsequent tokens
if (!token[n]) break; // no more tokens
}
}
// process (print) the tokens
for (int i = 0; i < n; i++) // n = #of tokens
cout << "Token[" << i << "] = " << token[i] << endl;
cout << endl;
}
}
来存储数据到数据库中看一看MySql
+1
谢谢,这将是非常有用的 – Hawk 2013-03-20 16:58:26
答
那么,你可以谷歌自己..但:只是做一些教程。 例如:http://www.cplusplus.com/doc/tutorial/files/ 而不是.TXT你只需打开.dat文件(既然你说只包含文本数据。)
在一个SQL数据库中存储的,我认为这将是MySQL的现在: http://www.nitecon.com/tutorials-articles/develop/cpp/c-mysql-beginner-tutorial/
对于步骤:打开你的文件,打开数据库连接,做一个INSERT INTO .... 完成。
你的问题提供足够的细节来回答:不存在“.dat文件格式”,'.dat'是一个通用的文件扩展名。没有“fstream库” - 你可能是指标准的库类“std :: fstream”,但这个问题是一个重复术语:是的,你使用它,但这不会帮助你。最后,你没有提供关于你正在处理的数据的信息,所以我们不知道如何将它们加载到SQL服务器中。 – 2013-03-20 15:56:32
@KonradRudolph文件包含文本,并以这种方式编写,当我将它们加载到数据库中时,每个文件将形成一个表格,它们包含|作为分隔符来分隔列,我可以手动将扩展名更改为txt并打开并读取它们,我需要知道如何编写C++代码来读取它们 – Hawk 2013-03-20 16:07:48
@jcarlos我之前没有处理过文件,所以如果您推荐一些简要教程我会很感激 – Hawk 2013-03-20 16:08:42