I have an application where I need to generate date and time based on the locale using the strftime function provided by C's time.h:
#include <stdio.h>
#include <time.h>
#include <locale.h>
#include<string.h>
int main()
{
//This is where date & time will be stored
char buffer[10];
// Set Japanese locale for LC_TIME
//Just an example, japanese takes 33 bytes. But the buffer I provided is of 10 bytes
// Installing japanese locale is another effort. So, instead of japanese you can try it by commenting the below setlocale. As even english date & time needs more space than 10.
setlocale(LC_TIME, "ja_JP.UTF-8");
// Initialize struct tm with some value, in this case September 26, 2025, at 12:27:05 PM
struct tm tm1 = {
.tm_sec = 5,
.tm_min = 27,
.tm_hour = 12,
.tm_mday = 26,
.tm_mon = 8,
.tm_year = 125,
.tm_wday = 5,
.tm_yday = 268,
.tm_isdst = 1
};
//In this case, len will be 0.
size_t len = strftime(buffer, sizeof(buffer), "%x %X", &tm1);
//From here, I want to send some error to my application which expects and throws an error to terminal, based on errno.h.
//ERANGE or EOVERFLOW or any other
}
The return value of strftime will be stored in rtnValue. If everything goes well, storeIn will contain the formatted date and time.
Different locales require different buffer sizes. However, there are cases where the date and time for a given locale can exceed the size specified by len. This can be mitigated by providing a larger buffer, but proper error handling is also necessary.
strftime does not set any specific error code like ERANGE or EOVERFLOW. Instead, it returns 0 when the provided buffer is too small, meaning no bytes were written. Due to requirements, I need to set an error code from errno.h. I am confused between ERANGE and EOVERFLOW.
EOVERFLOW sounds appropriate, and I have seen some implementations using it when a buffer overflow occurs. However, its description clearly states: “Value too large for defined data”, which suggests that the “too large” part refers to exceeding a data type’s limit rather than a manually set buffer size. Is my understanding correct? If so, this would not apply to my case.
ERANGE throws "Numerical result out of range" as the error, even though it is mostly used for math-related functions, certain websites state it as the input being outside the range which does sound right. But the error statement doesn't match with the issue.
Question:
What would be the most suitable error code for a situation like this?
Thank you in advance.
len - 1is odd.ERANGEwould be the most portable since it's required to exist by the C standard whileEOVERFLOWis not.ERANGEis not only mentioned in relation to math operations in the standard. It's used by conversion functions likestrtoimaxtoo.