John
John

Reputation: 11

strlen problems, returns the right length + 2

I have a weird bug.

I wrote a function that gets a file and returns the length of each line:

void readFile1(char *argv[], int fileNumber,
          char *array_of_lines[NUMBER_OF_LINES+1], int *currNumOfLines)
{
    FILE* fp;
    fp = fopen(argv[fileNumber], "r");
    if (fp == NULL)
    {
        fprintf(stderr, MSG_ERROR_OPEN_FILE, argv[fileNumber]);
        exit(EXIT_FAILURE);
    }
    char line[256];
    while (fgets(line, sizeof(line), fp))
    {
        printf("\n line contains : %s size is : %lu\n",line,strlen(line));
    }
}

The function always prints the right number + 2, For example if file.txt contains only one line with "AAAAA" the function would print that the length is 7 instead of 5,

 line contains : AAAAA
 size is : 7

Does someone know where is the bug?

Upvotes: 0

Views: 860

Answers (2)

pmg
pmg

Reputation: 108968

printf("\n line contains : %s size is : %lu\n",line,strlen(line));

Here's a giveaway

Obtained output

 line contains : AAAAA
size is : 7

Expected output

 line contains : AAAAA size is : 7

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409136

Don't forget that fgets leaves the newline in the buffer.

It seems you're reading a file created in Windows (where a newline is the two characters "\r\n") on a system where newline is only "\n". Those two characters are also part of the string and will be counted by strlen.


The reason I'm guessing you're reading a Windows-created file in a non-Windows system is because for files open in text-mode (the default) then the functions reading and writing strings will translate newlines from and to the operating-system dependent format.

For example on Windows, when writing plain "\n" it will be translated and actually written as "\r\n". When reading the opposite translation happens ("\r\n" becomes "\n").

On a system with plain "\n" line endings (like Linux or macOS), no translation is needed, and the "\r" part will be treated as any other character.

Upvotes: 5

Related Questions