1

In this related question How to use feof and ferror for fgets (minishell in C), the answers aren't really clear for my problem.

What I'm trying to do is: I want to read all of the characters from a plain text file on my disk. It's not a link, devicefile, socket etc. just a regular text file. Once I've read all the characters I want to see if everything succeeded. What I'm seeing now is, in my Debug builds everything goes successfully, but in my Release builds ferror() always indicates there is a an error. While the Debug build returns the 0 in the end. In both cases I can see that the content of the file has been obtained in a debugger.

my_function(File* f) {
    int c;
    while ((c = fgetc(f)) != EOF) {
        char character = (char) c;
        // store character in a dynamic growing buffer
    }
    // append '0' byte to buffer (to terminate the string).

    if (ferror(f)) {
        // return error
        return 1;
    }
    return 0; // no error.
}

Rationale of having a already opened file as function argument, is to make it relatively easy to read from a file, without the need to bother with a platform dependent encoding. This is inside a private part of my library, the public functions handle the case that f == NULL. Do I need to call clearerr(file) first, because the error bit is not initialized in a Release builds?

hetepeperfan
  • 4,292
  • 1
  • 29
  • 47
  • 2
    Different behavior in release and debug builds is typically an indication of having *undefined behavior* somewhere. – Some programmer dude Jan 22 '19 at 08:54
  • 1
    Use [`perror`](http://www.cplusplus.com/reference/cstdio/perror/) before `return 1;` and report back. Also the code you don't show may be buggy. A [mcve] might help here. – Jabberwocky Jan 22 '19 at 08:54
  • the C standard doesn't say anything about what might cause `ferror` to return non-zero, it's not anything you should try and rely on IMO – M.M Jan 22 '19 at 09:05
  • Yes, I'm sure i'm doing something wrong, but I'm haveing issues finding the right line inside of the debugger in release builds, since i'm not stepping in a linear fashion through the code. `perror` before `return 1;` isn't reached, so I'm afraid my error is somewhere else. – hetepeperfan Jan 22 '19 at 09:05
  • as an aside (unrelated to your question) : why not use [`fread`](https://en.cppreference.com/w/c/io/fread) ? – Sander De Dycker Jan 22 '19 at 09:07
  • @SanderDeDycker I, was hoping that that this way is easier. Maybe that was wrong, And should I just seek to the end, determine the file size and allocate a appropriate sized buffer and use fread to fill it. – hetepeperfan Jan 22 '19 at 09:13
  • @hetepeperfan : you don't need to read the entire file in one go - reading it in chunks will already give you a [nice performance improvement](https://stackoverflow.com/questions/13225014/why-fgetc-too-slow). – Sander De Dycker Jan 22 '19 at 09:26

0 Answers0