读取数据并重新格式化,按换行符

时间:2015-11-16 09:41:44

标签: c

数据文件由浮点数组成,我想重新格式化它。它有很多行(用'\ n'分隔),每行有很多浮点数(用空格分隔)。例如:

0.0  3.14 6.28 7.12
0.1  2.56 3.45 7.11
0.2  2.22 4.44 1.55

我尝试的代码如下:

#include <stdio.h>
int main(void)
{
    double num;
    FILE *fp, *fp_newFT;
    int index=-1;//t col

    fp=fopen("data.txt","r");
    fp_newFT=fopen("data-newFT.txt","w");

    while(fscanf(fp,"%lf",&num)==1)
    {
       if(index!=2)//!!!!problem code here!!!!
       {
           fprintf(fp_newFT,"%-14lf\t",num);
           index++;
       }
       else
       {
           fprintf(fp_newFT,"\n");
           index=-1;
       }
    }

    fclose(fp);
    fclose(fp_newFT);

    return 0;
}

输出结果为:

0.000000        3.140000        6.280000    
0.100000        2.560000        3.450000    
0.200000        2.220000        4.440000

如果我将条件行更改为:

if(index!=3)//!!!!problem code here!!!!

结果数据更加奇怪。

0.000000        3.140000        6.280000        7.120000    
2.560000        3.450000        7.110000        0.200000    
4.440000        1.550000 

我的代码有什么问题,以及如何修复它?

2 个答案:

答案 0 :(得分:1)

如果你想要的只是重新格式化文本,你应该使用modulo %运算符来打破这一行。

#include <stdio.h>
int main(void)
{
    double num;
    FILE *fp, *fp_newFT;

    int index=0;

    fp=fopen("data.txt","r");
    fp_newFT=fopen("data-newFT.txt","w");

    while(fscanf(fp,"%lf",&num)==1)
    {
        fprintf(fp_newFT,"%-14lf\t",num);
        index++;
        if( !(index % 4 ) )
        {
            fprintf(fp_newFT,"\n");
        }
    }

    fclose(fp);
    fclose(fp_newFT);

    return 0;
}

输出:

0.000000        3.140000        6.280000        7.120000        
0.100000        2.560000        3.450000        7.110000        
0.200000        2.220000        4.440000        1.550000        

答案 1 :(得分:0)

我们仍然不知道你想要完成什么,但是为了阅读这些数据,我建议做这样的事情:

#include <stdio.h>
#include <string.h>

#define MAX_LINE_LENGTH 1000

int main(void)
{
    double num;
    FILE *fp, *fp_newFT;
    char lineBuf[MAX_LINE_LENGTH];

    if (!(fp = fopen("data.txt", "r")))
    {
        // handle error
    }


    if (!(fp_newFT = fopen("data-newFT.txt", "w")))
    {
        // handle error
    }

    while (fgets(lineBuf, sizeof(lineBuf), fp))
    {
        char* tok = strtok(lineBuf, " ");

        while (tok != NULL)
        {
            if (!sscanf(tok, "%lf", &num))
            {
                // handle error (bad input)
            }

            // do whatever you want with the numbers, here I just write them to the new file with fixed width precision
            fprintf(fp_newFT, "%.8f\t", num);

            tok = strtok(NULL, " ");
        }

        // add a newline
        fprintf(fp_newFT, "\n");
    }

    fclose(fp);
    fclose(fp_newFT);

    return 0;
}

然后您可以根据需要将其写入输出文件。请记住检查I / O函数的返回值,以便正确处理错误。