0

So I want to read 2 lines from a .csv file,but for some reason when there is another empty line,fgets reads it as well which means I get an extra loop which I dont want. When I try to break the loop by checking if the first element of the buffer array (which if I understand correctly,is "refreshed" after every execution of the fgets command,didn't find much info on this) is Null or the New Line character,nothing happens. The .csv looks like this:

Title,Year,Genre,CastSize,Actors
Movie 1,1991,Genre 1,2,[Actor 1,Actor 2]

Code like this:

for (;!feof(fp);){
   fgets(buffer,500,fp);
   if (buffer[0]=='\n' || buffer[0]=='\0'){break;}
   ......

(When the extra blank line isn't there in the .txt,I get my two loops done correctly.)

  • If you want to continue processing the file after the blank line, why are you using `break`? – Scott Hunter Jan 01 '22 at 23:32
  • I dont,I just want to read those 2 lines and store them in respective nodes of a singly linked list. The third line,as long as its empty,I dont want it to affect me. – kakas123455 Jan 01 '22 at 23:35
  • 1
    If `fgets()` reads an empty line, the buffer will hold `"\n\0"` (assuming the buffer is at least 2 bytes in size). But as stated the use of `feof()` is incorrect *and* you failed to check the return value from `fgets` which is `NULL` when there is no more data to be read. The idiomatic control loop is `while(fgets(buffer, sizeof buffer, fp) != NULL) { ...}` – Weather Vane Jan 02 '22 at 00:02
  • kakas123455, Who or what texted suggested `for (;!feof(fp);){`? – chux - Reinstate Monica Jan 02 '22 at 00:06

0 Answers0