0
char *myfgets(char *s, int n, FILE *in) {
    char ch;
    if (n<=0) {
        return s;
    }
    while (((ch = getc(in)) != '\n')) {
        if(ch == EOF){
            return NULL;
        }
        else if (ch == '\n') {
            break;
        } else {
            *s=ch;
            s++;
        }
    }
    *s = '\n';
    if (ferror(in) != 0) {
        return NULL;
    } else {
        return s;
    }   
    
    if (strlen(s) > 512) {
        return NULL;
    }
}

I want to take 1 line only from some specific file and put the line into the char pointer (*s). I made this function but when I run the program it didn't work really well. For the result, there are a lot of unknown characters that are displayed.

Is there anything wrong with my code?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    Could you please also mention what exact output you got from which input? – loonatick Apr 18 '22 at 02:50
  • 1
    Returning `s` when `n <= 0` is not a good idea; return 0 or NULL to indicate a problem. – Jonathan Leffler Apr 18 '22 at 03:13
  • See [`while ((c = getc(file)) != EOF)` won't stop executing?](https://stackoverflow.com/q/13694394/15168). The return type of `getc()` et al is `int` because the functions can return 256 distinct character values and one extra value — and you can't fit 257 distinct values in an 8-bit `char`. – Jonathan Leffler Apr 18 '22 at 03:15
  • You should check that you're not going to write beyond the end of the array (remembering that you need to add a null byte to indicate the end of the string, all within the `n` bytes you're given to work with). You check a number of conditions, but you don't check that one. It needs to be in the loop somewhere. (Corollary: if `n == 1`, you can't read any data into the buffer.) – Jonathan Leffler Apr 18 '22 at 03:16
  • 1
    `int ch, count = 0;` and `if (n < 1) { return NULL; }` (you must have room for the `'\0'`) and then `while (count < n - 1 && ((ch = getc(in)) != '\n')) { ... s++; count += 1; ... }` Also consider changing `n` and `count` to `size_t`) – David C. Rankin Apr 18 '22 at 03:25

1 Answers1

0

From the man page of strlen():

The strlen() function calculates the length of the string pointed to by s, excluding the terminating null byte ('\0').

So, strlen counts the number of characters until it finds a null byte '\0', and not the newline character '\n'. Consider changing

*s = '\n'

to

*s = '\0'

Alternatively, you could write your own strlen that looks for '\n' instead of '\0'.

loonatick
  • 648
  • 1
  • 7
  • 15