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?

5
  • 1
    Could you please also mention what exact output you got from which input? Commented Apr 18, 2022 at 2:50
  • 1
    Returning s when n <= 0 is not a good idea; return 0 or NULL to indicate a problem. Commented Apr 18, 2022 at 3:13
  • See while ((c = getc(file)) != EOF) won't stop executing?. 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. Commented Apr 18, 2022 at 3: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.) Commented Apr 18, 2022 at 3: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) Commented Apr 18, 2022 at 3:25

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.