0

I don't know why while loop can't stop. It can't compare c with Delim neither stop by reaching eof.

wchar_t* Getline(const wchar_t* Filename, const wchar_t Delim){

FILE* f = _wfopen(Filename, L"r, ccs=UTF-8");

wchar_t* info = NULL;
wchar_t* temp = NULL;
int count = 1;
int i = 0;
wchar_t c;

c = fgetwc(f);

while (c != Delim || !feof(f))
{
    count++;
    temp = (wchar_t*)realloc(info, count * sizeof(wchar_t));

    if (temp)
    {
        info = temp;
        info[i] = c;
        i++;
    }

    else
    {
        free(info);
        wprintf(L"Failed to read\n");
    }
    c = fgetwc(f);
}
info[i] = '\0';

fclose(f);
return info;

}

After reading all character in file. It seem not to stop. Even c are the same with Delim. And !feof(f) hasn't worked too. I have try c != WEOF but fail too

I thought that the problem is in the file that I read but not. I have change another file but the same problem. Thanks for helping me!

  • regarding: `FILE* f = _wfopen(Filename, L"r, ccs=UTF-8");`, always check (!=NULL) the value in `f` to assure the operation was successful. – user3629249 Apr 15 '18 at 16:42
  • when calling any of the heap allocation functions `malloc` `calloc` `realloc` 1) the returned type is `void*`, so can be assigned to any pointer. Casting just clutters the code, making it more difficult to understand, debug, etc Suggest removing the cast – user3629249 Apr 15 '18 at 17:08
  • strongly suggest inserting: `perror( L"realloc failed" ); free( info ); exit( EXIT_FAILURE )' as the code in the `else` code block. otherwise the code will continue to loop. At best, one char of the input will be lost. More likely, once `realloc()` fails, it will continue to fail. – user3629249 Apr 15 '18 at 17:19
  • function: fgetwc() returns a `wint_t`, not a `wchar_t`. – user3629249 Apr 15 '18 at 17:31
  • suggest the while loop be written as: `while ( (c = fgetwc(f)) !=WEOF && (wchar_t)c != Delim )` Which makes use of the possible error indication from the call to `fgetwc()` – user3629249 Apr 15 '18 at 20:20

1 Answers1

1

You wish to loop whilst you have not got a Delim character and it is not the end of the file, so replace the || with &&

while (!feof(f) && c != Delim)

Edit: the order has also been changed in response to comments

vogomatix
  • 4,856
  • 2
  • 23
  • 46