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?
swhenn <= 0is not a good idea; return 0 or NULL to indicate a problem.while ((c = getc(file)) != EOF)won't stop executing?. The return type ofgetc()et al isintbecause the functions can return 256 distinct character values and one extra value — and you can't fit 257 distinct values in an 8-bitchar.nbytes 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: ifn == 1, you can't read any data into the buffer.)int ch, count = 0;andif (n < 1) { return NULL; }(you must have room for the'\0') and thenwhile (count < n - 1 && ((ch = getc(in)) != '\n')) { ... s++; count += 1; ... }Also consider changingnandcounttosize_t)