0
votes

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.

3
Take the tour, read How to Ask and minimal reproducible example. Can you strip that code down to the smallest example that demonstrates the problem?jwdonahue
You are calling fgets and feof on an output stream, what did you expect to happenM.M
Ya, I was tracking on that with the original post, then all the code changed in front of me. I think the OP has their guzzintas crossed over with their cumzoutas. But while(!feof()) is just wrong anyway.jwdonahue
@topcat you cannot read from a file opened with mode "w"M.M

3 Answers

3
votes

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)
0
votes

fp2 was opened in write mode "w", So it must be closed then opened in read mode "r" so lines could be read properly, people could have spotted that instead of saying its the While(!feof(fp2)).

-1
votes

I believe this is well addressed here, it will solve if you replace while(!feof(fp2)) ---> while(!feof(fp2) && !ferror(fp2))