从文本文件中读取值?

时间:2017-02-12 03:45:44

标签: c

我在文本文件中有以下格式的数据

WA5362288SeaTac city         25496    10176      434224    9.964121    0.167655 47.441406-122.293077
WA5363000Seattle city       563374   270524   151956998   83.872647   58.670927 47.626353-122.333144

现在我尝试从上面的数据中提取特定值(删除了一些填充空格),例如

WA SeaTAC 47.441406 -122.293077

我不确定如何在通过文本文件流式传输时从C中的特定列获取值

    FILE *fp;
    fp = fopen("places.txt", "r");

    if(fp == NULL){
            fprintf(stderr, "Can't open the file");
            exit(1);
    }

    while(!feof(fp)){
       //extract values from specific column
       //fscanf()
    }

1 个答案:

答案 0 :(得分:3)

我假设您的文件包含以下内容:

WA 5362288 SeaTac city         25496    10176      434224    9.964121    0.167655 47.441406 -122.293077
WA 5363000 Seattle city       563374   270524   151956998   83.872647   58.670927 47.626353 -122.333144

让文件名为simple.txt。然后,以下代码符合您的目的:

   #include <stdio.h>

FILE *fp;

int main()
{
   char buff1[80],buff2[80];
   char buff3[80];
   int num,num1,num2,num3 ;
   float num4,num5,num6,num7;
   fp = fopen("simple.txt", "r");
    if(fp == NULL){
            fprintf(stderr, "Can't open the file");
            exit(1);
    }
    while(fscanf(fp, "%19s %d %19s %19s %d %d %D %f %f %f %f ", buff1,&num,buff2,buff3,&num1,&num2,&num3,&num4,&num5,&num6,&num7)!= EOF)
       printf("%s %d %s %s %d %d  %d %f %f %f %f \n",buff1,num,buff2,buff3,num1,num2,num3 ,num4,num5,num6,num7);


   fclose(fp);
}

此代码打印文件内容,如下所示:

WA 5362288 SeaTac city 25496 10176  434224 9.964121 0.167655 47.441406 -122.293076
WA 5363000 Seattle city 563374 270524  151956998 83.872650 58.670925 47.626354 -122.333145

希望这会有所帮助。