前言
- 关于linux下ls命令的简要模拟,可参考
http://blog.csdn.net/stpeace/article/details/45252897 - 关于C/C++读写csv文件,可参考
http://blog.csdn.net/u012234115/article/details/64465398
Linux检索目录的文件(模拟ls)
可以使用include <dirent.h>
头文件下的opendir、readdir函数;
例如检索当前目录下以“ID_”开头的所有文件,如下:
DIR *fd; // 指向目录
struct dirent *dirp; // 指向目录中的对象
if((fd = opendir("./")) == NULL)
{
printf("不存在的路径或权限不足!\n");
return -1;
}
// 读取目录中的对象, 然后打印出其名字d_name
while((dirp = readdir(dp)) != NULL)
{
if(strstr(dirp->d_name, "ID_") != NULL){
printf("%s\n", dirp->d_name);
}
}
closedir(dp); // 关闭目录
写csv文件
csv文件其实就是文本文件,每行字段用逗号分隔。
引入头文件#include <fstream> #include <sstream>
,使用ofstream类中的成员函数可以更加方便地实现写csv文件;代码如下:
ofstream outFile;
outFile.open("data.csv", ios::out);
outFile << "name" << ',' << "age" << ',' << "hobby" << endl;
outFile << "Mike" << ',' << 18 << ',' << "paiting" << endl;
outFile << "Tom" << ',' << 25 << ',' << "football" << endl;
outFile.close();
整合
1. 整合多个txt文件到csv文件的代码
[TXTtoCSV.cpp]:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <dirent.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
/*txt文件中取出字符串的最大长度*/
#define MAXLEN 1024
/*获取一个文件中所有的文本信息并转换为一个字符串*/
int GetStrFromFile(const char* fileName, string& oData){
FILE* fd = fopen(fileName, "rb");
if (fd == NULL){
printf("打开文件失败!!\n");
return -1;
}
char lineBuff[MAXLEN];
fseek(fd, 0L, SEEK_SET);
while(!feof(fd)){
if(fgets(lineBuff, sizeof(lineBuff)-1, fd)){ //获取一行数据
oData.append(lineBuff);
}
}
fclose(fd);
return 0;
}
/*复制 src中首次出现换行'\n'长度的字符串 到dest中*/
int myStrCpy(char *dest, char *src){
int len=0;
memset(dest, '\0', MAXLEN);
while(src[len] != '\n' && len < MAXLEN){
len++;
}
if(len > 0)
memcpy(dest, src, len);
else
return -1;
return 0;
}
int main()
{
char *p, *tempStr;
string strId;
tempStr = (char *)malloc(MAXLEN);
ofstream outFile;
outFile.open("data.csv", ios::out);
outFile << "DeviceID,SecretKey"<< endl;
char path[200], filePath[200];
DIR *dp; // 指向目录
struct dirent *dirp; // 指向目录中的对象
printf("请输入操作路径:");
scanf("%s", path);
if((dp = opendir(path)) == NULL)
{
printf("不存在的路径或权限不足: %s\n", path);
return -1;
}
// 读取目录中的对象
while((dirp = readdir(dp)) != NULL)
{
if(strstr(dirp->d_name, "ID_") != NULL){
strId.erase();
memcpy(filePath, path, strlen(path)+1);
//连接目录名称与该目录下的文件生成绝对路径
strcat(filePath, dirp->d_name);
GetStrFromFile(filePath, strId);
p = strstr((char *)strId.c_str(), "PhyId=");
if(p!=NULL){
p+=strlen("PhyId=");
if(myStrCpy(tempStr, p) == 0){
outFile<<tempStr<<endl;
}else{
printf("\n%s:不存在PhyId\n", dirp->d_name);
}
}
}
}
printf("\ndata.cvs 生成成功!!\n");
free(tempStr);
outFile.close();
return 0;
}
2. 编译
g++ TXTtoCVS.cpp -o TXTtoCVS
3. 运行
4. csv生成结果
版权声明:本文为博主原创文章,未经博主允许不得转载