简体   繁体   中英

Making myfgets using char pointer as an input

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM