Search code examples
cexecutionerrno

Difference between the execution sequence of two outputs of perror function in C


Difference between output sequence on the same code on removing "\n"

#include<stdio.h>
#include<errno.h>
#include<string.h>


int main()
{
FILE * fp;
fp = fopen("GeeksForGeeks", "/root/C");
printf("Value of error no : %d\n", errno);
printf("The error message is : %s\n", strerror(errno));
perror("Message from perror.");
return 0;
}

This is my code but when I remove the "\n", the sequence of execution of perror changes. Can anyone explain why?


Solution

  • Most likely, stdout is in linebuffered mode so it flushes on \n, and perror writes to stderr.

    Adding fflush(stdout); before the perror call will fix it.