-1

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
genpfault
  • 51,148
  • 11
  • 85
  • 139
xNapz
  • 7
  • 1

1 Answers1

3

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
Craig Estey
  • 30,627
  • 4
  • 24
  • 48
  • And be wary of [trailing white space in `scanf()` format strings](https://stackoverflow.com/q/19499060/15168). Here, where the data comes from a file, it is probably not a problem unless someone is careless enough to provide `/dev/tty` as the file name instead of `file.txt`, but in general, it is a bad idea. – Jonathan Leffler Dec 13 '22 at 21:25