I run this code: (On Ubuntu 16.04 with VMware)
#include <stdio.h>
#include <string.h>
#define ARRAY_SIZE 50
int main()
{
char str[ARRAY_SIZE];
int i;
FILE* fp = fopen("test.txt", "r");
if(fp == NULL)
{
printf("File hasn't opened.\n");
return 1;
}
while(fgets(str, ARRAY_SIZE, fp) != NULL)
{
printf("str length is %d\n", strlen(str));
for(i = 0; i < strlen(str); i++)
printf("index is %d, char is %d\n", i, str[i]);
}
fclose(fp);
return 0;
}
test.txt
has only 1 character in it (the character '1'), no newline character after the only character.
Why strlen(str)
returns 2 and not 1?
And why the second character is a newline character if there's no newline character in test.txt?