从C中的另一个文件创建一个新文件

时间:2013-04-25 22:19:22

标签: c file fopen scanf printf

我有一个这种格式的文件:

0.4
0.3
0.2
0.4

我需要使用以下格式创建一个新文件:

1 2

0.4 1 0
0.5 1 0 
0.3 0 1 
... 

我写了这个函数

void  adapta_fichero_serie(char file_input[50],char file_output[50], int np)
{

    FILE* val_f=fopen(file_input,"r");
    FILE* out_f=fopen(file_output,"w+");
    float temp[np+1];
    float tempo;
    int i=0;
    int uno=1;
    int flag=0;
    int due=2;
    int zero=0;
    int file_size;

    fprintf(out_f,"%d %d\n", np, due );

    while(!feof(val_f))
    {
        if(flag==0)
        {
            for(i=0;i<np;i++)
            {
                fscanf(val_f,"%f" ,&tempo);
                temp[i]=tempo;
                flag=1;
            }
        }

        fscanf(val_f,"%f",&tempo);
        temp[np]=tempo;

        for(i=0;i<np;i++)
        {
            fprintf(out_f,"%f\t",temp[i]);
        }

        if(temp[np-1]<=temp[np]) 
        fprintf(out_f,"%d\t%d ", uno, zero);
        else fprintf(out_f,"%d\t%d\n", zero, uno);  

        for(i=0;i<np;i++)
        {   
            tempo=temp[i+1];
            temp[i]=tempo;
        }
    }

    close(out_f);
    close(val_f);

}

并创建具有正确格式的新文件,但是当我尝试读取此新文件时,读取在第315行停止,但文件为401行。 你能帮助我吗?我希望我的问题很容易理解!

2 个答案:

答案 0 :(得分:1)

只是要从评论中记录您的解决方案,请使用fclose而不是close,并确保注意您的编译器警告,因为他们会指出这一点。

答案 1 :(得分:0)

不确定您的算法应该做什么。以下是我对此的看法:)

void adapta_fichero_serie(const char *file_input, const char *file_output)
{
    float n_prev, n_cur; // Processed values as we read them
    FILE *in, *out; // Input-output files

    n_prev = 0; // Initial value for the first element to compare with

    in = fopen(file_input, "rt"); // open read only in text mode
    out = fopen(file_output, "wt+"); // append in text mode

    fprintf(out, "1\t2\n\n"); // write header: 1 <TAB> 2 <CR><CR>

    while (fscanf(in, "%f", &n_cur) == 1)  // run loop as long as we can read
    {
        fprintf(out, n_cur > n_prev ? "1\t0\n" : "0\t1"); // print depending on comparison
        n_prev = n_cur; // save value for the next iteration
    }

    fclose(in);
    fclose(out);
}
相关问题