Harsh Wardhan Harsh Wardhan -3 years ago 89
C Question

Loop exit condition on fgets doesn't work

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.

Answer Source

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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download