The standard library function fgets()
has two downsides:
- The second parameter of the function is of type
int
- It leaves a trailing new-line character in the supplied buffer
I have made a simple function similar to fgets()
excluding the above-mentioned downsides, to try to improve the efficiency of one of my programs that fetches the lines of a text file and terminates the char
array at the new-line character using the function strcspn()
.
But is it really more efficient? Is there any reason why the standard library function has advantage over the following naive implemention?
#include <stdio.h>
char *my_fgets(char *buf, size_t maxCount, FILE *stream);
int main(int argc, char **argv)
{
if (argc < 2)
{
fprintf(stderr, "Usage: %s [filename]", argv[0]);
}
FILE *fp;
fp = fopen(argv[1], "r");
if (!fp)
{
perror(argv[1]);
return 1;
}
char buf[256];
/*while (fgets(buf, sizeof(buf), fp))
{
buf[strcspn(buf, "\n")] = '\0';
// . . .
puts(buf);
}*/
while (my_fgets(buf, sizeof(buf) - 1, fp))
{
puts(buf);
}
return 0;
}
char *my_fgets(char *buf,
size_t maxCount, FILE *stream)
{
int ch;
size_t n = 0;
while ((ch = fgetc(stream)) != EOF)
{
if (ch == '\n' || n == maxCount)
{
break;
}
else
{
buf[n++] = ch;
}
}
if (n == 0 && ch == EOF)
{
return NULL;
}
buf[n] = '\0';
return buf;
}