【问题标题】:copying data from text file to the another将数据从文本文件复制到另一个
【发布时间】:2015-02-01 01:25:54
【问题描述】:

我有一个如下所示的文本文件:

;3;untyped;31.1948;29.917 
;3;untyped;31.195;29.9168 
;3;untyped;31.195;3;29.9167 
;3;untyped;31.1955;29.9166

我想将它复制到另一个文本文件中,如下所示:

number_of_lines lat1 long1 t1 lat2 long2 t2 lat3 long3 t3.....

其中 t 从 1 开始,每次递增 1。

这是我的代码:

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

int main()
{   
    FILE *file2 = fopen("out.txt", "w");
    int NOL=1;
    char ch;
    FILE *file1 = fopen("in.txt", "r");     
    while((ch=fgetc(file1))!=EOF)                  //loop to find out how many lines are in the text file
    {
        if (ch=='\n') { NOL++; }
    }
    printf("number of lines = %d \n",NOL);
    fclose(file1);

    char line[100];
    int inc = 1;
    FILE *file3 = fopen("in.txt", "r"); 
    fprintf(file2,"%d ",NOL);
    for(int i=0;i<NOL;i++)
    {
        fscanf(file3,"%s\n",line);       
        char *trash1 = strtok(line, ";");      //ignoring the first part
        printf("%s\n",trash1);

        char *trash2 = strtok(NULL, ";");        //ignoring the second part
        printf("%s\n",trash2);

        char *lat = strtok(NULL, ";");
        float lat_f = atof(lat);                //storing the lat
        printf("%s\n",lat); 

        char *lon = strtok(NULL, ";");
        float lon_f = atof(lon);             //storing the long
        printf("%s\n",lon); 

        fprintf(file2,"%f %f %d ",lat_f,lon_f,inc);    //printing the values to the output text file
        inc++;
    }
    fclose (file3); 
    fclose (file2);     
}

当我运行我的代码时,一些复制的值没有被正确复制,如下所示

4 31.194799 29.917000 1 31.195000 29.916800 2 31.195000 **3.000000** 3 31.195499 29.916599 4 

为什么会这样?代码有问题吗?请问如何解决。

【问题讨论】:

  • 请务必检查 fopen() 的结果
  • 在这里按预期工作。输入文件中的补充3; 是错字吗?
  • 我同意@MichaelWalz,额外的3;是问题所在。您可能想检查每一行是否有正确数量的值......如果没有,您可以处理忽略或将行标记为无效?

标签: c text copying


【解决方案1】:

在您的示例 4 行中,第 3 行包含字段 4 3; 中的其他数据,这就是您的“意外”3 的来源。

【讨论】:

  • 是的,这是一个错字:S。真的很抱歉
【解决方案2】:

你的第三行有一个可选的;,所以输出是正确的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多