我只是开发简单的逻辑来解析;
分隔文件,如下所示,并将其内容插入数据库。
它工作正常,但在INSERT
语句的最后一次迭代中,我收到此错误:
selfdiag4.0.1(157):未定义指令:pc = 020000fa非法指令(核心转储)。
我的代码如下:
int fileread() {
char str1[1024];
unsigned char catId[25]="",catName[50]="",prefix[25]="",status[10]="";
char *ptr;
char temp[1024];
int i=1,t,rc=0;
char delims[]=";";
char filename[100] ="/mnt/jffs2/category.txt";
FILE *fp;
rc=0;
fp= fopen("/mnt/jffs2/category.txt","r");
if (fp == NULL) {
printf("No such file");
return 1;
}
while(fgets(str1,sizeof(str1),fp) !=NULL) {
ptr=strtok(str1,delims);
while(ptr != NULL) {
i=1;
memset(catId,0,sizeof(catId));
memset(catName,0,sizeof(catName));
memset(prefix,0,sizeof(prefix));
memset(status,0,sizeof(status));
while(ptr!=NULL && i<=8) {
strcpy(temp, ptr);
ptr = strtok(NULL,delims);
switch(i) {
case 2: strcpy(catId,temp);
break; //insert into categoryId
case 4: Strcpy(catName,temp);
break;
case 6: Strcpy(prefix,temp);
break;
case 8: strcpy(status,temp);
break;
default:break;
} //end switch
i++;
} //end while
rc=execute("INSERT INTO category(category_id,category_name,prefix,status) VALUES('%s','%s','%s','%s');",catId,catName,prefix,status);
printf("\nIn While Loop\n");
if (rc == 0) return error_handler(rc);
} // end while
}
fclose(fp);
return 0;
}
答案 0 :(得分:1)
#include <stdio.h>
#include <string.h>
/* these are for testing */
#define execute printf
#define error_handler(i) fprintf(stderr, "Error(%d)\n", i )
int fileread(char *filename )
{
char buff[1024];
size_t off,len, cnt;
char *ptrs[10];
int rc=0;
char delims[]=";\n\r";
FILE *fp;
fp= fopen(filename, "r");
if (fp == NULL) {
fprintf(stderr, "No such file: %s\n", filename);
return 1;
}
while(fgets(buff,sizeof buff,fp) ) {
for(cnt=off = 0; buff[off] ; off+= len ) {
ptrs[cnt++] = buff + off;
len = strcspn(buff+off, delims );
if (!len) break;
buff[len+off] = '\0';
len += 1;
if (cnt >= 10) { fprintf(stderr, "Too many items\n" ); break; }
}
if (cnt < 8) continue;
/* if you expect repeating groups,
** you should iterate here. And resize ptrs[] */
rc=execute(
"INSERT INTO category(category_id,category_name,prefix,status)"
" VALUES('%s','%s','%s','%s');\n"
,ptrs[1],ptrs[3],ptrs[5],ptrs[7]);
if(rc == 0)return error_handler(rc);
}
fclose(fp);
return 0;
}
int main(void)
{
char *filename ="/mnt/jffs2/category.txt";
int rc;
rc = fileread (filename);
return 0;
}