I want to achieve

I want to read data with an unknown number of lines and write it to a csv file, but I write a completely different value. Please give me some advice.

Data I want to read
      1, 3.88000000e-003, -9.50325916e-019, 1.40000000e-002
        2, 3.88000000e-003, -9.50325916e-019, 1.50000000e-002
        3, -3.88000000e-003, 4.75162958e-019, 1.50000000e-002
        4, -3.88000000e-003, 4.75162958e-019, 1.40000000e-002
        5, 3.22000000e-003, -7.88672539e-019, 1.50000000e-002
・ ・ ・
Corresponding source code
int main (void) {
    FILE * fp1;
    FILE * fp2;
    int f1;
    double f2, f3, f4;
    int c;
    int line = 0;
    int i;
    fp1 = fopen ("test.txt", "r");
    fp2 = fopen ("ndData.csv", "w");
    if (fp1 == NULL) {
        printf ("Your ndData file can't be found! \ N");
        return (-1);
    while ((c = fgetc (fp1))! = EOF) {
        if (c =='\ n') line ++;
    printf ("% d \ n", line);
    for (i = 1;i<= line;i ++) {
        fscanf (fp1, "% d,% le,% le,% le",&f1,&f2,&f3,&f4);
    fprintf (fp2, "Total node numbers:% d \ n", line);
    for (i = 1;i<= line;i ++) {
        fprintf (fp2, "% 4d,% 12.5e,% 12.5e,% 12.5e \ n", f1, f2, f3, f4);
    fclose (fp1);
    fclose (fp2);
    return (0);
c c++
  • Answer # 1

    fgetcsoEOFI've read up to, so the file ends there. Even though there is no more datafscanfEven ifEOFJust returns.fscanfThe return value ofEOFI haven't checked if it is, so I'm not aware of it.
    f1The contents of variables such as are the first garbage.

    If you read it twice, it will be easier for beginners to close it and reopen it.

    Also, even if you fix it
    Since I'm overwriting the same variable when reading, I'm just writing the last read data for the number of lines.
    Let's repeat "read one line and write one line".

    fscanfBe sure to check the return value of the input function.