【发布时间】: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;是问题所在。您可能想检查每一行是否有正确数量的值......如果没有,您可以处理忽略或将行标记为无效?