-3

我有一个 csv 文件,看起来像这样:

  1. 1;53453;45847865
  2. 1;37567;53687686
  3. .
  4. .
  5. .
  6. . n. 1;999768;5645644

我想打开文件,阅读它,然后将每一行拆分为 3 个标记,这些标记将与分号隔开....

例如

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);  

    }
4

2 回答 2

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;
}
于 2013-03-27T21:21:42.407 回答
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);
}

如果你想跳过第一行然后添加一个 integr 参数并初始化为 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. 如果 csv 文件中每一行的字符串格式看起来像这样, "1. 25;78;547"" %*d . %d ; %d ; %d"fscanf()
  2. 如果您的 csv 文件中每一行的字符串格式看起来像这样, "25;78;547"那么您必须" %d ; %d ; %d"fscanf()
于 2013-03-27T20:35:58.760 回答