Hi,
I can't figure out how fgetln(3)() works. Here is the code:
input.txt:
The output:
Why bytes read and strlen(line) are not equal? I expect that fgetline(3)() just returns a pointer to the first line of the file (although without ending "\0", as described in the manual page), but why the whole content of the file is printed?
I can't figure out how fgetln(3)() works. Here is the code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
int main(void)
{
char *line;
char *fname = "/path/to/input.txt";
size_t *length;
FILE *in;
in = fopen(fname, "r");
if (in == NULL)
{
printf("Error opening the file\n");
exit(EXIT_FAILURE);
}
line = fgetln(in, length);
printf("bytes read: %zd\n", *length);
if( line == NULL )
{
printf("file is empty\n");
exit(EXIT_FAILURE);
}
else
printf("strlen(line): %zd\n", strlen(line));
printf("The content: \n%s", line);
fclose(in);
return 0;
}
input.txt:
Code:
Hello
This is the first line.
And this is the second line.
This one is the last line.
The output:
Code:
[CMD]% ./a.out [/CMD]
bytes read: 6
strlen(line): 86
The content:
Hello
This is the first line.
And this is the second line.
This one is the last line.
Why bytes read and strlen(line) are not equal? I expect that fgetline(3)() just returns a pointer to the first line of the file (although without ending "\0", as described in the manual page), but why the whole content of the file is printed?