Search code examples
cdebuggingwhile-loopfgets

When does fgets stop reading a line?


I am debugging my program using gdb, fgets(line, sizeof(line), fp2) reads nothing from a text file. so the program loops infinity ins side while(!feof(fp2)) and the EOF is never met i dont know why?

I'm putting part of the code for context,

here is the inputfile:

  COPY   START  1000
  FIRST  STL    RETADR
  CLOOP  JSUB   RDREC
         LDA    LENGTH
         COMP   ZERO
         JEQ    ENDFIL
  ZERO   WORD   0
  RETADR RESW   1
  LENGTH RESW   1
  BUFFER RESB   4096



         RSUB
         END    FIRST

here is the main program:

int main(int argc, char *argv[])
{

    FILE *fp, *fp2, *fphex;
    char line[1000] = "" ;


    if (argc != 2)
    {
        printf("Usage: %s filename\n", argv[0]);
        exit(EXIT_FAILURE);
    }


    if ((fp = fopen(argv[1], "r")) == NULL)
    {
        printf("Can't open %s\n", argv[1]);
        exit(EXIT_FAILURE);
    }

    fp2 = fopen("intermediate.asm", "w");
    fp2 = removecomment(fp,fp2);
    rewind(fp2);

    while (!feof(fp2))
    {
        fgets(line, sizeof(line), fp2);   /*this fgets reads only 4 bytes of empty spaces*/ 
        parse(line);

    }
    struct node *print = head;
    fphex = fopen("Hex_code", "w");

    while(print == NULL)
    {
        fprintf(fphex, "%s", print->instruction);
        print = print->next;
    }

    return(0);
}

EDIT:

While(!feof(File*pointer) was not the problem.

i was trying to read from a write only fopen file.

i resolved it by fclose(file) fopen("file","r") or as suggested by others w+ mode. I think closing and opening in read mode is safer.


Solution

  • Ok, here is the problem, you have "w" as a file opening mode.

    fp2 = fopen("intermediate.asm", "w");
    

    it should be

    fp2 = fopen("intermediate.asm", "r");
    

    file opening modes are

    1. w - write (file is deleted if exists)
    2. r - read (file must exist)
    3. a - append

    than you have + sign which means:

    1. w+ - write and read (overwrite if file exists)
    2. r+ - read and write (file must exist)
    3. a+ - append and read (create file if it does not exist)