getting error file format incorrect, reading file in c

56 Views Asked by At

if i run 1 data, program execution is success. but in 2 data format file incorrect. where did i go wrong?

File .txt

1,Nanggroe Aceh Darussalam,Rumah Sakit,RSU Cut Nyak Dhien,Jl. Tm Bahrum No. 1 Langsa
2,Jawa Barat,Klinik Utama,dr. Sunarhadi,Raya Cikaret No. 12

Read code

do{
    read = fscanf(file,
                    "%d,%100[^,],%100[^,],%100[^,],%100[^,]\n",          
                    &students[records].no, 
                    students[records].prov, 
                    students[records].tipe, 
                    students[records].nama,
                    students[records].alamat); 

    if (read == 5) records++;
    
    if (read != 5 && !feof(file)){
      printf("File format incorrect.\n");
      return 1;
    }
    
    if (ferror(file)){
      printf("Error reading file.\n");
      return 1;
    }

  } while (!feof(file));

Output says

File format incorrect.

How can i output like

No      : 1
Prov    : Nanggroe Aceh Darussalam
Tipe    : Rumah Sakit
Nama    : RSU Cut Nyak Dhien
Alamat  : Jl. Tm Bahrum No. 1 Langsa

No      : 2
Prov    : Jawa Barat
Tipe    : Klinik Utama
Nama    : dr. Sunarhadi
Alamat  : Raya Cikaret No. 12
1

There are 1 best solutions below

1
On

The format is incorrect. It expects a trailing comma on the lines.

Change:

"%d,%100[^,],%100[^,],%100[^,],%100[^,]\n"

Into:

"%d,%100[^,],%100[^,],%100[^,],%100[^\n]\n"

Notes:

  1. Never use feof. Just check the return value of fscanf and ensure it's equal to 5. See: Why is “while( !feof(file) )” always wrong?
  2. You check ferror but never show what errno is in your printf