Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop exit condition on fgets doesn't work [duplicate]

I have a text file like this

"input"
height : 227
width : 227
depth : 3

"conv"
num_output : 96
pad : 0
kernel_size : 11
stride : 4
group : 1

"relu"

"pool"
kernel_size : 3
stride : 2

I'm reading it in a loop (this is partial code)

char line[100];

while ((fgets(line, sizeof(line), filePtr))) {
    if (line[0] != "\n") {
        sscanf(line, "%15s : %15s", tmpstr1, tmpstr2);
        printf("%s\n",  tmpstr2);
        printf("line = %s", line);
    } else
        break;
}

But I observed that the if condition always holds true and the output is as below

"input"
227
line = height : 227
227
line = width : 227
3
line = depth : 3
3
line = 
3
line = "conv"
96
line = num_output : 96
0
line = pad : 0
11
line = kernel_size : 11
4
line = stride : 4
1
line = group : 1
1
line = 
1
line = "relu"
1
line = 
1
line = "pool"
3
line = kernel_size : 3
2
line = stride : 2

I have tried comparison with \0 as well but the result doesn't change. Please point me where I'm going wrong.

P.S. : I'm using Ubuntu 16.04 64-bit machine with gcc 5.2.1.

like image 521
Harsh Wardhan Avatar asked Apr 18 '26 07:04

Harsh Wardhan


2 Answers

Newline is a character, not a string, so change this:

line[0] != "\n"

to this:

line[0] != '\n'

Enable compiler warnings (-Wall flag in GCC) and you should see something like this:

warning: comparison between pointer and integer
warning: comparison with string literal results in unspecified behavior [-Waddress]
like image 161
gsamaras Avatar answered Apr 19 '26 23:04

gsamaras


You are trying to compare an string literal with char.

With:

if(line[0] != '\n')

It works well.

If you're reading from a file that's been opened in text mode (including stdin), then whatever representation the underlying system uses to mark the end of a line will be translated to a single '\n' character.

You should turn on compiler warnings. For gcc it's -pedantic -Werror.

like image 28
kocica Avatar answered Apr 19 '26 22:04

kocica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!