Saad A Saad A - 7 months ago 53
C Question

C: fgets return an extra blank line at beginning

I am trying to read a file and reverse each line of it and display it to standard output in C.

my file is :

$ cat f1
this is line 1
this is line 2
this is line 3

My code is:


void reverse_string(char* s)
int l = strlen(s);
int i;
char sr[l];
int j = 0;

for(i= l-1; i >= 0; i--)
sr[j] = s[i];
printf("%s", sr);

int main(int argc, char *argv[])

FILE *fp;
int i;
char filename[128];
char line[100];

for(i = 1; i < argc; i++)
strcpy(filename, argv[i]);

fp = fopen(filename, "r");

while(fgets(line, 128, fp) != NULL)
if(strlen(line) != 0)


Output is:

$ ./mycode f1
(blank line here)
1 enil si siht
2 enil si siht
3 enil si siht

I am confused, why is there a extra blank line being output by my while loop even though there is no blank line in the file.

Answer Source

fgets includes a '/n' before nul char.

So when you reverse a string, the first thing you do is print it.

My ugly fix is:

replace the fist printf with

printf("%s\n", sr+1);

remove the second one.

And remember, when all fails, read the manual.:

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s.

Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer.

A terminating null byte ('\0') is stored after the last character in the buffer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download