Search code examples
objective-ccmacosfgets

why fgets not work?


I installed a new version of os X (10.7 initially and then updated to 10.7.5) - I lost man fgets in Terminal, it no longer exists(not olny fgets, some other too). I'm using xcode 4.6.3, updated all kinds of documentation. In documentation i got only FGETS(3), not fgets! When i write this code:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    FILE *wordFile = fopen ("/tmp/words.txt", "r");
    char word[100];
    while (fgets(word, 100, wordFile))
    {
        word[strlen(word) - 1] = '\0';          // strip off the trailing \n
        NSLog (@"%s is %lu characters long", word, strlen(word));
    }

    fclose (wordFile);
    return 0;
}

i got output:

Joe-Bob "Handyman" Brown
Jacksonville "Sly" Murphy
Shinara Bain
George "Guitar" Book is 84 characters long

Why?


Solution

  • My money on @Martin R.

    fgets() did not find a converted \n in file "/tmp/words.txt" even though it was open in text mode "t". The editor used to create/edit the file is ending the lines with \r.

    See @Michael Haren in Do line endings differ between Windows and Linux?

    BTW: word[strlen(word) - 1] = '\0'; is potentially a problem, though not in this case, as strlen(word) may be 0. (@wildplasser)