Making myfgets using char pointer as an input

61 Views Asked by At
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?

1

There are 1 best solutions below

0
On

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'.