在C中排序CSV文件

时间:2014-10-30 08:23:54

标签: c sorting csv

你好我做了一个程序,将传感器中的数据读入csv文件。

void sensor_read(int fd)
{

    FILE *fp;
    char c;
    do{
        while(!read(fd, &c, 1));
        printf("%c\n",c);
    }while (c!='$');

    do{
        while(!read(fd, &c, 1));
        fp = fopen("/var/www/Sensor_data.txt", "a");
        fprintf(fp, "%c%", c);
        printf("%c",c);
        fclose(fp);
    }while (c!='\n');
}

读取的数据如下所示: MEAS,587.088518,的 1.093652,1.988754,3522.934999,3522.013512,690.454784,896.428414,115.473813 下,23.875225,14.871661,2.847579,805.726416

我只需要标记7个值,所以我的问题是从文件中检索这些数据的好方法是什么?要在编写文件时执行此操作,还是在文件创建完成后将其保存到新文件中?也许是一些如何做到这一点的例子:)

提前谢谢!

2 个答案:

答案 0 :(得分:0)

double values[7] = {0};
fscanf(fp, "meas,%*lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf", &values[0],  &values[1],
     &values[2], &values[3], &values[4], &values[5], &values[6]);

答案 1 :(得分:0)

void sensor_read(int fd )
{

    FILE *fp;
    char c;
    double values[7] = {0};
    fp = fopen("/var/www/Sensor_data.txt", "w");
    do {
        while(!read(fd, &c, 1));
        printf("%c\n",c);

        fscanf(fp, "meas,%*lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf", &values[0],  &values[1],&values[2], &values[3], &values[4], &values[5], &values[6]);
    } while (c!='$');

    do {
        while(!read(fd, &c, 1));

        //fscanf(fp, "meas,%*lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf", &values[0],  &values[1],
        //&values[2], &values[3], &values[4], &values[5], &values[6]);

        //fprintf(fp, "%lf,%lf,%lf,%lf,%lf,%lf,%lf\n", &values[0],  &values[1],
        //&values[2], &values[3], &values[4], &values[5], &values[6]);

        printf("%lf,%lf,%lf,%lf,%lf,%lf,%lf\n", &values[0],  &values[1], &values[2], &values[3], &values[4], &values[5], &values[6]);


    } while (c!='\n');

    fclose(fp);
}

来自传感器的输入是:

$meas,587.088518,1.093652,1.988754,3522.934999,3522.013512,690.454784,896.428414,115.473813,23.875225,14.871661,2.847579,805.726416