Search code examples
cfgetsfeofferror

Edit: How many char does fgets consider from *stream, when passing to its char *str?


I have been sitting on this simple fundamental mistake for a while. How do we avoid strings in the stdin, that are bigger than a defined sizeof(sring). Here sizeof(stdin_passed) > sizeof(word_new). Furthermore we are restricted to the use of, ferror an/or feof.

Thanks in advanced

Edit: Hint is, there is no \n character, i will try to work with it

Edit 2: The Segmentation Error ocurred, because of a piece of code that was not shown. My fault.

Edit 3: We don't avoid anything. We take as much characters as allowed by char *str size. We are aware that char *str can end with '\n' or any char. This might be helpful, because strings end with the char '\0'.


int main() {

    char word_new[42];

    while(1) {
        /*help needed here: ouput is Segmentation Error*/

        if (fgets(word_new, sizeof(word_new), stdin) == NULL){
            // error occurs, thus use perror
            if(ferror(stdin)){
                perror("error occured in stdin");
                exit(1);
            }
            // no error and only EOF reached
            break;
        }

//not previously provided snippet:

char *wordpt = strchr(word_new, '\n');
*wordpt = '\0';

//no '\n' character => error


Solution

  • You can quite easily check it yourself:

    int main(void) 
    {
    
        char word_new[5];
        int loopno = 0;
        char *result = word_new;
    
        while(result) 
        {
            /*help needed here: ouput is Segmentation Error*/
    
            if ((result = fgets(word_new, sizeof(word_new), stdin)))
            {
                printf("Loop no: %d\n", ++loopno);
                for(size_t index = 0; index < sizeof(word_new) && word_new[index]; index++)
                {
                    printf("word_new[%zu] - '%s' Code: % 3hhd (0x%02hhx)\n", index, isprint(word_new[index]) ? (char [2]){word_new[index], 0} : "NP", word_new[index], word_new[index]);
                }
            }
        }
    }
    

    and the result for 1234567890 is self explanatory

    Loop no: 1
    word_new[0] - '1' Code:  49 (0x31)
    word_new[1] - '2' Code:  50 (0x32)
    word_new[2] - '3' Code:  51 (0x33)
    word_new[3] - '4' Code:  52 (0x34)
    Loop no: 2
    word_new[0] - '5' Code:  53 (0x35)
    word_new[1] - '6' Code:  54 (0x36)
    word_new[2] - '7' Code:  55 (0x37)
    word_new[3] - '8' Code:  56 (0x38)
    Loop no: 3
    word_new[0] - '9' Code:  57 (0x39)
    word_new[1] - '0' Code:  48 (0x30)
    word_new[2] - 'NP' Code:  10 (0x0a)
    

    https://godbolt.org/z/9MYerPf67

    I strongly recommend writing similar tiny programs at your stage if you do not understand something.