0

The reason why I have written this post is because no other post on SO solves my problem. I've read all the posts on this subject and tried/tested the suggestions, but they dont work in the context of the code I posted - hence the post in the first place...

I have the following function and it give an extra loop at the end, adding another byte to the end of the string Im creating. I've tried adding -1 to the loop variable, but it nothing seems to get rid of this extra loop. Is feof the right choice for this exercise, or is fgetc better? If so, how can I use fgetc in the context of my function?

void do_file(FILE *in, FILE *out, OPTIONS *options)
{
    char ch;
    int loop = 0;
    char buf[81];
    buf[0] = '\0';

    int seeker = offsetof(struct myStruct, contents.datas);

    fseek(in, seeker, SEEK_SET);

    fprintf(out, "%i", seeker);

    while (options->max == -1 || loop < options->max)
    {
        if (feof(in))
        {
            break;
        }

        if (loop % 16 == 0)
        {
            if (strlen(buf) > 0)
            {
                buf[0] = '\0';
            }
        }

        fread(&ch, 1, 1, in);
        fprintf(out, "%02X", (int)(ch & 0x00FF));

        if (isalnum(ch))
        {
            char tmp[2];
            tmp[0] = ch;
            tmp[1] = '\0';
            strcat(buf, tmp);
        }

        loop++;
    }
}
Ke.
  • 2,484
  • 8
  • 40
  • 78
  • 2
    `feof` shouldn't be used to control loop. – ameyCU Sep 11 '16 at 07:46
  • I realise this, but Im trying to figure out alternatives in the context of my function, because while I can see examples, they dont relate to my function - thats what Im struggling with. A big help would be to show an example within my function as an answer rather than a comment – Ke. Sep 11 '16 at 07:47
  • 1
    See this, maybe it will help: http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong – Adrian Roman Sep 11 '16 at 07:48
  • @Ke. To loop through you can check `return` of `fread` in case to identify error or `EOF`. And another good alternative would be to use `fgets` and read file line by line . – ameyCU Sep 11 '16 at 07:48
  • I cant read line by line, because the whole function runs over each byte. I tried return of fread, but couldnt get it to work - any examples? – Ke. Sep 11 '16 at 07:51
  • Thx adrian roman, had read that fully before I came here, still struggling though – Ke. Sep 11 '16 at 07:51
  • What do you mean by "couldn't get it to work"? How hard is it to test the return value of a function? – melpomene Sep 11 '16 at 09:56
  • Use `fgets` for text file. – i486 Sep 11 '16 at 12:26

0 Answers0