Search code examples
ctextcopying

copying data from text file to the another


I have a text file that looks like this:

;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

I want to copy it to another text file so that looks like this:

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

where t begins at 1 and increments by 1 each time.

This is my code:

#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);     
}

When i run my code, some of the copied values aren't copied correctly, as seen below

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

Why does that happen? Is there something wrong with the code? How can I fix it please.


Solution

  • your third line has an optional ;, so the output is correct