我要打开文件,阅读它然后将每一行拆分为3个令牌,这些令牌将从分号中分离出来....
e.g
1; 35435; 75675
token1 = 1;
token2 = 35435;
token3 = 75675;
我拥有的代码是一个主要的,我打开并读取文件和一个函数,我手动一串字符并拆分它...
#include<stdio.h>
int main(){
char c;
FILE *fp;
char line;
float x;
float y;
if((fp=fopen("test.csv","r"))==NULL){
printf("cannot open the file");
}else{
do{
c = fscanf (fp, "%c", &line);
printf("%c" , line);
}while(c!=EOF);
fclose(fp);
}
}
的 的 __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ -
int TokenX(char line) {
char *id;
char *x;
char *y;
char line[] = "1;345345;765767";
char *search = ";";
id = strtok(line , search);
// printf(id);
x = strtok(NULL , search);
printf(x);
y = strtok(NULL , search);
printf(y);
return(x);
}
int TokenY(char line) {
char *id;
char *x;
char *y;
char line[] = "1;345345;765767";
char *search = ";";
id = strtok(line , search);
// printf(id);
x = strtok(NULL , search);
printf(x);
y = strtok(NULL , search);
printf(y);
return(y);
}
答案 0 :(得分:0)
您可以将fscanf()
与while
一起使用。 while循环中的每次迭代都将从文件中读取一行。
int token1, token2, token3;
while(fscanf(fp, " %*d . %d ; %d ; %d", &token1, &token2, &token3)>0)
{
printf("%d %d %d\n",token1, token2, token3);
}
如果你想跳过第一行然后添加一个积分参数并启动为0.当你输入while循环时检查它是否等于0
int token1, token2, token3;
int check = 0;
while(fscanf(fp, " %*d . %d ; %d ; %d", &token1, &token2, &token3)>0)
{
if(!check) {check++; continue;}
printf("%d %d %d\n",token1, token2, token3);
}
"1. 25;78;547"
使用以下格式" %*d . %d ; %d ; %d"
在fscanf()
"25;78;547"
比您必须使用以下格式" %d ; %d ; %d"
fscanf()
答案 1 :(得分:0)
琐碎的状态机:
#include <stdio.h>
int main(void)
{
char token1[123];
char token2[123];
char token3[123];
unsigned nline;
int ch,state;
char *dst=token1;
nline=0;
for (state=0; state >=0; ) {
ch = getc(stdin);
// fprintf(stderr, "Line=%u State=%d Ch=%c\n", nline, state, ch);
switch(ch) {
case EOF :
state = -1; break;
case ';' :
if (dst) *dst = 0;
switch(state++) {
case 0: dst = token2; break;
case 1: dst = token3; break;
default: dst = NULL; break;
}
break;
case '\n' :
nline++;
if (dst) *dst = 0;
// if you want to skip the first line
if (state>=2 && nline> 1) printf("%s:%s:%s\n"
, token1, token2 ,token3);
state =0; dst = token1; break;
default: *dst++ = ch; break;
}
}
return 0;
}