CAPL 按行读取 CSV 文件并切分字符串
切分字符串
首先CAPL中并没有内置的类似 C 中 strtok 的函数,有两种方法可以实现
- 将 strtok 封装到 CAPL DLL 中,然后调用
- 自己造个轮子,如下
参考:https://blog.csdn.net/qq_34414530/article/details/121209670
做了一些修改用于处理特殊的场景
int spilt_string(char input_string[],char out_string_arrary[][],char sign[])
{
int i ;
int debug;
int StartIndexPos;
char p_index[20];
int out_arrary_length ;
debug = 1;
StartIndexPos = 0;
out_arrary_length = 1;
p_index[0] = 0;
do{
StartIndexPos = strstr_off(input_string,StartIndexPos+1,sign);
p_index[out_arrary_length] = StartIndexPos;
if (StartIndexPos!=-1)
out_arrary_length ++;
} while(StartIndexPos!=-1);
p_index[out_arrary_length] = strlen(input_string)-1;
for(i=0;i<out_arrary_length;i++)
{
if(i==0 && p_index[i+1] - p_index[i] == 1){
substr_cpy(out_string_arrary[i], input_string, p_index[i], p_index[i+1] - p_index[i], elcount(out_string_arrary[i]));
}
else if(i==0){
substr_cpy(out_string_arrary[i], input_string, p_index[i], p_index[i+1] - p_index[i], elcount(out_string_arrary[i]));
}
else if(i==out_arrary_length-1){
substr_cpy(out_string_arrary[i], input_string, p_index[i]+1, p_index[i+1] - p_index[i], elcount(out_string_arrary[i]));
}
else{
substr_cpy(out_string_arrary[i], input_string, p_index[i]+1 , p_index[i+1] - p_index[i] -1, elcount(out_string_arrary[i]));
}
if (debug){
//write("serched postion:%d", p_index[i]);
write("out_string_arrary[%d]:%s", i,out_string_arrary[i]);
}
}
return out_arrary_length;
}
读取文件
主要用到的函数是自带的 openFileRead 和 fileGetString(类似C中的 fgets 按行读取)
on key 'b'{
dword fh;
char row[80];
char out_string_arrary[80][80];
long glbValue;
fh = openFileRead("C:\\Users\\Desktop\\test.csv", 0);
if(fh!=0){
write("open file success");
while ( fileGetString(row,elcount(row),fh)!=0 ) {
write ("Row is: %s.",row);
spilt_string(row,out_string_arrary,",");
}
fileClose (fh);
}
else{
write("open file failed");
}
}
Output:
Row is: 1,2,3,4,5
out_string_arrary[0]:1
out_string_arrary[1]:2
out_string_arrary[2]:3
out_string_arrary[3]:4
out_string_arrary[4]:5
写入文件
on key 'b'{
dword fh;
char data[7] = {'a', ',','b', ',','b', ',', '\n'}
setWritePath("C:\\Users\\Desktop"); // need set write path first when use write file
fh = openFileWrite("test.csv", 2);
if(fh!=0){
write("open write file success");
filePutString (data, elcount(data),fh);
fileClose (fh);
}
else{
write("open write file failed");
}
}