What does «LC_ALL=C» do?
What does the C value for LC_ALL do in Unix-like systems? I know that it forces the same locale for all aspects but what does C do?
- environment-variables
- locale
72.1k 34 34 gold badges 193 193 silver badges 226 226 bronze badges
asked Aug 22, 2013 at 7:32
9,702 16 16 gold badges 55 55 silver badges 75 75 bronze badges
If you want to resolve a problem with xclock warning( Missing charsets in String to FontSet conversion ), it will be better if you will use LC_ALL=C.UTF-8 to avoid problems with cyrillic. To set this environment variable you must add the following line to the end of ~/.bashrc file — export LC_ALL=C.UTF-8
Jun 19, 2019 at 12:42
@fedotsoldier you should probably ask question and give the answer yourself, I don’t think it’s related to the question. It’s just answer to different problem you’re having.
Jun 19, 2019 at 13:20
Yeah, you are right, ok
Jun 19, 2019 at 13:22
legendary C locales rant github.com/mpv-player/mpv/commit/…
Sep 4, 2022 at 6:28
6 Answers 6
LC_ALL is the environment variable that overrides all the other localisation settings (except $LANGUAGE under some circumstances).
Different aspects of localisations (like the thousand separator or decimal point character, character set, sorting order, month, day names, language or application messages like error messages, currency symbol) can be set using a few environment variables.
You’ll typically set $LANG to your preference with a value that identifies your region (like fr_CH.UTF-8 if you’re in French speaking Switzerland, using UTF-8). The individual LC_xxx variables override a certain aspect. LC_ALL overrides them all. The locale command, when called without argument gives a summary of the current settings.
For instance, on a GNU system, I get:
$ locale LANG=en_GB.UTF-8 LANGUAGE= LC_CTYPE="en_GB.UTF-8" LC_NUMERIC="en_GB.UTF-8" LC_TIME="en_GB.UTF-8" LC_COLLATE="en_GB.UTF-8" LC_MONETARY="en_GB.UTF-8" LC_MESSAGES="en_GB.UTF-8" LC_PAPER="en_GB.UTF-8" LC_NAME="en_GB.UTF-8" LC_ADDRESS="en_GB.UTF-8" LC_TELEPHONE="en_GB.UTF-8" LC_MEASUREMENT="en_GB.UTF-8" LC_IDENTIFICATION="en_GB.UTF-8" LC_ALL=
I can override an individual setting with for instance:
$ LC_TIME=fr_FR.UTF-8 date jeudi 22 août 2013, 10:41:30 (UTC+0100)
$ LC_MONETARY=fr_FR.UTF-8 locale currency_symbol €
Or override everything with LC_ALL.
$ LC_ALL=C LANG=fr_FR.UTF-8 LC_MESSAGES=fr_FR.UTF-8 cat / cat: /: Is a directory
In a script, if you want to force a specific setting, as you don’t know what settings the user has forced (possibly LC_ALL as well), your best, safest and generally only option is to force LC_ALL.
The C locale is a special locale that is meant to be the simplest locale. You could also say that while the other locales are for humans, the C locale is for computers. In the C locale, characters are single bytes, the charset is ASCII (well, is not required to, but in practice will be in the systems most of us will ever get to use), the sorting order is based on the byte values¹, the language is usually US English (though for application messages (as opposed to things like month or day names or messages by system libraries), it’s at the discretion of the application author) and things like currency symbols are not defined.
On some systems, there’s a difference with the POSIX locale where for instance the sort order for non-ASCII characters is not defined.
You generally run a command with LC_ALL=C to avoid the user’s settings to interfere with your script. For instance, if you want [a-z] to match the 26 ASCII characters from a to z , you have to set LC_ALL=C .
On GNU systems, LC_ALL=C and LC_ALL=POSIX (or LC_MESSAGES=C|POSIX ) override $LANGUAGE , while LC_ALL=anything-else wouldn’t.
A few cases where you typically need to set LC_ALL=C :
- sort -u or sort . | uniq. . In many locales other than C, on some systems (notably GNU ones), some characters have the same sorting order. sort -u doesn’t report unique lines, but one of each group of lines that have equal sorting order. So if you do want unique lines, you need a locale where characters are byte and all characters have different sorting order (which the C locale guarantees).
- the same applies to the = operator of POSIX compliant expr or == operator of POSIX compliant awk s ( mawk and gawk are not POSIX in that regard), that don’t check whether two strings are identical but whether they sort the same.
- Character ranges like in grep . If you mean to match a letter in the user’s language, use grep ‘[[:alpha:]]’ and don’t modify LC_ALL . But if you want to match the a-zA-Z ASCII characters, you need either LC_ALL=C grep ‘[[:alpha:]]’ or LC_ALL=C grep ‘[a-zA-Z]’ ². [a-z] matches the characters that sort after a and before z (though with many APIs it’s more complicated than that). In other locales, you generally don’t know what those are. For instance some locales ignore case for sorting so [a-z] in some APIs like bash patterns, could include [B-Z] or [A-Y] . In many UTF-8 locales (including en_US.UTF-8 on most systems), [a-z] will include the latin letters from a to y with diacritics but not those of z (since z sorts before them) which I can’t imagine would be what you want (why would you want to include é and not ź ?).
- floating point arithmetic in ksh93 . ksh93 honours the decimal_point setting in LC_NUMERIC . If you write a script that contains a=$((1.2/7)) , it will stop working when run by a user whose locale has comma as the decimal separator:
$ ksh93 -c 'echo $((1.1/2))' 0.55 $ LANG=fr_FR.UTF-8 ksh93 -c 'echo $((1.1/2))' ksh93: 1.1/2: arithmetic syntax error
Then you need things like:
#! /bin/ksh93 - float input="$1" # get it as input from the user in his locale float output arith() < typeset LC_ALL=C; (($@)); >arith output=input/1.2 # use the dot here as it will be interpreted # under LC_ALL=C echo "$output" # output in the user's locale
As a side note: the , decimal separator conflicts with the , arithmetic operator which can cause even more confusion.
- When you need characters to be bytes. Nowadays, most locales are UTF-8 based which means characters can take up from 1 to 6 bytes³. When dealing with data that is meant to be bytes, with text utilities, you’ll want to set LC_ALL=C. It will also improve performance significantly because parsing UTF-8 data has a cost.
- a corollary of the previous point: when processing text where you don’t know what character set the input is written in, but can assume it’s compatible with ASCII (as virtually all charsets are). For instance grep ‘<.*>‘ to look for lines containing a < , >pair will no work if you’re in a UTF-8 locale and the input is encoded in a single-byte 8-bit character set like iso8859-15. That’s because . only matches characters and non-ASCII characters in iso8859-15 are likely not to form a valid character in UTF-8. On the other hand, LC_ALL=C grep ‘<.*>‘ will work because any byte value forms a valid character in the C locale.
- Any time where you process input data or output data that is not intended from/for a human. If you’re talking to a user, you may want to use their convention and language, but for instance, if you generate some numbers to feed some other application that expects English style decimal points, or English month names, you’ll want to set LC_ALL=C:
$ printf '%g\n' 1e-2 0,01 $ LC_ALL=C printf '%g\n' 1e-2 0.01 $ date +%b août $ LC_ALL=C date +%b Aug
That also applies to things like case insensitive comparison (like in grep -i ) and case conversion ( awk ‘s toupper() , dd conv=ucase . ). For instance:
grep -i i
is not guaranteed to match on I in the user’s locale. In some Turkish locales for instance, it doesn’t as upper-case i is İ (note the dot) there and lower-case I is ı (note the missing dot).
Notes
¹ again, only on ASCII based systems (the immense majority of systems). POSIX requires the collation order for the C locale to be that of the order of characters in the ASCII charset, even on EBCDIC systems which are not allowed to do the strcoll() === strcmp() optimisation in the C locale.
² Depending on the encoding of the text, that’s not necessarily the right thing to do though. That’s valid for UTF-8 or single-byte character sets (like iso-8859-1), but not necessarily non-UTF-8 multibyte character sets.
For instance, if you’re in a zh_HK.big5hkscs locale (Hong Kong, using the Hong Kong variant of the BIG5 Chinese character encoding), and you want to look for English letters in a file encoded in that charsets, doing either:
LC_ALL=C grep '[[:alpha:]]'
LC_ALL=C grep '[a-zA-Z]'
would be wrong, because in that charset (and many others, but hardly used since UTF-8 came out), a lot of characters contain bytes that correspond to the ASCII encoding of A-Za-z characters. For instance, all of A䨝䰲丕乙乜你再劀劈呸哻唥唧噀噦嚳坽 (and many more) contain the encoding of A . 䨝 is 0x96 0x41, and A is 0x41 like in ASCII. So our LC_ALL=C grep ‘[a-zA-Z]’ would match on those lines that contain those characters as it would misinterpret those sequences of bytes.
LC_COLLATE=C grep '[A-Za-z]'
would work, but only if LC_ALL is not otherwise set (which would override LC_COLLATE ). So you may end up having to do:
grep '[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]'
if you wanted to look for English letters in a file encoded in the locale’s encoding.
³ some would argue it’s rather 1 to 4 bytes these days now that Unicode code points (and the libraries that encode/decode UTF-8 data) have been arbitrarily restricted to code points U+0000 to U+10FFFF (0xD800 to 0xDFFF excluded) down from U+7FFFFFFF to accommodate the UTF-16 encoding, but some applications will still happily encode/decode 6-byte UTF-8 sequences (including the ones that fall in the 0xD800 .. 0xDFFF range).
Answer c что это
Для пользователей программ для чтения экрана: вы работаете в режиме просмотра, оптимизированном для мобильных устройств, в связи с чем контент может не отображаться там, где вы ожидаете его увидеть. Чтобы вернуться в режим просмотра для настольных компьютеров, разверните окно браузера до максимального размера.
Закрыть меню переходов
Ваш профиль в LinkedIn
Последнее обновление: 2 года назад
Профиль в LinkedIn представляет собой целевую страницу специалиста, позволяющую вам управлять своим личным брендом. Это отличный способ рассказать людям о себе и своих занятиях, продемонстрировав достижения и историю трудовой деятельности. Используйте профиль LinkedIn, чтобы добавить к своему образу характерные черты, которые может не отражать обычное резюме.
LinkedIn предлагает различные функции на основе сведений из вашего профиля и профилей других участников, чтобы помочь вам в достижении поставленных целей. Максимально заполненный профиль в LinkedIn поможет вам находить новые возможности.
Примечание. Многие используют слово «профиль» как синоним учетной записи LinkedIn.
Отредактируйте профиль, надлежащим образом организовав отображаемые в нем сведения, чтобы максимально эффективно использовать свою учетную запись.
Доступные для отображения разделы профиля
Раздел с основными сведениями – самый верхний раздел профиля, в котором представлена информация о вашем текущем личном и профессиональном статусе. Он содержит следующие данные:
Опыт работы – профессиональный опыт, в том числе текущие и прошлые места работы, волонтерские проекты, военная служба, места в советах директоров, посты в некоммерческих организациях и профессиональные занятия спортом.
Образование – сведения о среднем и высшем образовании.
Лицензии и сертификаты – полученные вами сертификаты, лицензии и допуски.
Навыки – список ваших навыков в профиле помогает другим людям узнать о ваших сильных сторонах и позволяет им легче находить вас.
Рекомендации – вы можете запросить рекомендации о своей профессиональной деятельности у ваших коллег.
Курсы – добавление списка пройденных курсов поможет вам выделиться среди других участников.
Звания и награды – полученные вами награды.
Языки – языки, которые вы понимаете и на которых говорите.
Организации – расскажите о своем участии в жизни сообществ, имеющих для вас большое значение.
Патенты – ваши полученные или оформляемые патенты.
Публикации – публикации, связанные с вашей профессиональной деятельностью.
Проекты – список проектов, над которыми вы работали, с указанием других участников команды.
Результаты тестирования – список пройденных вами тестов вместе с результатами как свидетельство ваших высоких достижений.
Волонтерский опыт – расскажите о своей волонтерской деятельности.
Узнайте подробнее, как приступить к созданию профиля и как создать свой бренд, чтобы выделяться на фоне остальных.
Answer Back Code for Inm-C, Inm-B
Вообще-то Answer Back — это для телексов. про Инмарсат впервые слышу, никогда там такого понятия не было, если я что-то догоняю вообще.
El-Vital
коллежский секретарь
Зарегистрирован: 13 янв 2011, 13:26
Сообщения: 122
Откуда: Таллин
Должность: Электромеханик
Тип судов: Газовозы
Репутация: 23
MiK 16 фев 2011, 10:03
Зарегистрирован: 11 июн 2010, 21:39
Сообщения: 31
Откуда: Smolensk
Должность: Старший помощник
Тип судов: Нефтяные танкера
Репутация: 0
El-Vital 16 фев 2011, 10:05
так что именно интересует? если вопрос «где взять?», так это дело провайдера связи а не экипажа
El-Vital
коллежский секретарь
Зарегистрирован: 13 янв 2011, 13:26
Сообщения: 122
Откуда: Таллин
Должность: Электромеханик
Тип судов: Газовозы
Репутация: 23
MiK 16 фев 2011, 11:05
Nashol! Inm C sent msg me to me and for inm b in tlf menu-setup-DMG. Spasibo chto otkliknulis’.
Зарегистрирован: 11 июн 2010, 21:39
Сообщения: 31
Откуда: Smolensk
Должность: Старший помощник
Тип судов: Нефтяные танкера
Репутация: 0
inginer 24 фев 2011, 13:08
У Inmarsat есть официальный сайт http://www.inmarsat.com/ .
Там очень много полезной информации , в том числе и troubleshoting, что означает решение возникших проблем.Там есть back коды для телексов. Даю ссылку http://www.inmarsat.com/Support/Inmarsa . only=False
Дело в том, что telex это такая система, которая выдает сообщение, особенно об ошибке, ввиде кода, и его надо расшифоровать, для этого есть таблица. И члены экипажа, отвечающие за связь, поскольку уже в чистом виде таких нет, узких спецов, должны знать, как работает, а иначе, как знать что произошло. Даю расшифровку кода ниже. Если что, спрашивай:
Inmarsat C non-delivery notification (NDN) failure codes
This is a selection of non-delivery notification (NDN) codes used by some Inmarsat C land earth station (LES) operators. In addition to, or instead of, these codes, some LES operators may use their own codes or messages. To find out the particular NDN codes / messages used by a specific LES operator, and their meanings, contact the LES operator’s customer services department directly.
ABS — Absent subscriber. The mobile terminal is not logged in to the ocean region.
ACB — Access barred.
ADR — Addressee refuses to accept message.
ANU — Deleted. The message has not been delivered within an hour and is therefore deleted.
ATD — Attempting to deliver the message.
BK — Message aborted. Is used when a fax or PSTN-connection is cleared abnormally.
BUS — Busy.
CCD — Call cut or disconnected.
CI — Conversation impossible.
CIE — The LESO ran out of processing / communications capacity to process the message.
CNS — Call not started.
DTE — Data terminal equipment. Used when an X.25 subscriber has cleared the connection during the call attempt.
ERR — Error.
FAU — Faulty.
FMT — Format error.
FSA — Fast select acceptance not subscribed.
IAB — Invalid answer-back from destination.
IAM — Was unable to process the address information in the following message:
IDS — Invalid data from ship.
IDT — Input data time-out.
IFR — Invalid facility request.
IMS — Message size is invalid; 7,932 characters maximum.
IND — Incompatible destination.
INH — Was unable to establish the type of message from the following header:
INV — Invalid.
ISR — Invalid ship request.
LDE — Maximum acceptable message length or duration has been exceeded.
LEF — Local equipment failure.
LPE — Local procedure error.
MBB — Message broken by higher priority.
MCC — Message channel congestion.
MCF — Message channel failure.
MKO — Message killed by operator.
MSO — Machine switched off.
NA — Correspondence with this subscriber is not permitted.
NAL — No address line is present.
NC — No circuits.
NCH — Subscriber’s number has changed.
NDA — No delivery was attempted.
NFA — No final answer-back.
NIA — No initial answer-back.
NOB — Not obtainable.
NOC — No connection.
NP — No party. The called party is not, or is no longer, a subscriber.
NTC — Network congestion/
OAB — Operator aborted.
OCC — Subscriber is occupied.
OOO — Out of order.
PAD — Packet assembler / disassembler.
PRC — Premature clearing.
PRF — Protocol failure.
RCA — Reverse charging acceptance not subscribed.
REF — There was a failure in the remote equipment.
RLE — Resource limit exceeded.
RPE — Remote procedure error.
RPO — RPOA out of order.
SCC — Call completed successfully.
SHE — MES hardware error.
SNF — The satellite network has failed.
SPE — MES protocol error.
SUC — Test results being delivered.
TBY — Trunks busy.
TGR — TDM group reset.
TIM — Time-out.
TMD — Too many destinations.
UNK — Unknown. Is used when no other failure codes are suitable.
WFA — Wrong final answer-back.
WIA — Wrong initial answer-back.
C++ Creator Bjarne Stroustrup Answers Our Top Five C++ Questions

Mariel Frank and Sonny Li, authors of Codecademy’s Learn C++ course, recently got a chance to interview with Dr. Bjarne Stroustrup, the creator of C++. As part of the interview, he answered the highest voted C++ questions on Stack Overflow. While the whole interview is worth a read, Codecademy has generously allowed us to republish the Q&A portion of the interview. If you ever wondered if an answer on Stack Overflow was definitive, here’s about the closest you’ll get to certain (though we expect somebody to disagree).
Why is processing a sorted array faster than processing an unsorted array?

That sounds like an interview question. Is it true? How would you know? It is a bad idea to answer questions about efficiency without first doing some measurements, so it is important to know how to measure. So, I tried with a vector of a million integers and got:
Already sorted 32995 milliseconds Shuffled 125944 milliseconds Already sorted 18610 milliseconds Shuffled 133304 milliseconds Already sorted 17942 milliseconds Shuffled 107858 milliseconds
I ran that a few times to be sure. Yes, the phenomenon is real. My key code was:
void run(vector& v, const string& label) < auto t0 = system_clock::now(); sort(v.begin(), v.end()); auto t1 = system_clock::now(); cout (t1 — t0).count() void tst() < vectorv(1'000'000); iota(v.begin(), v.end(), 0); run(v, "already sorted "); std::shuffle(v.begin(), v.end(), std::mt19937< std::random_device<>() >); run(v, "shuffled "); >
What is the —> operator in C++?

That’s an old trick question. There is no —> operator in C++. Consider:
if (p-->m == 0) f(p);
It certainly looks as if there is a —-> operator and by suitable declaring p and m, you can even get that to compile and run:
int p = 2; int m = 0; if (p-->m == 0) f(p);
That means: see if p— is greater than m (it is), and then compare the result (true) to 0. Well true != 0, so the result is false and f() is not called. In other words:
if ((p--) > m == 0) f(p);
Please don’t waste too much time on such questions. They have been popular for befuddling novices since before C++ was invented.
The Definitive C++ Book Guide and List

Unfortunately, there is no definite C++ book list. There can’t be one. Not everyone needs the same information, not everyone has the same background, and C++ best practices are evolving. I did a search of the web and found a bewildering set of suggestions. Many were seriously outdated and some were bad from the start. A novice looking for a good book without guidance will be very confused! You do need a book because the techniques that make C++ effective are not easily picked up from a few blogs on specific topics—and of course blogs also suffer from mistakes, being dated, and poor explanations. Often, they also focus on advanced new stuff and ignore the essential fundamentals. I recommend my Programming: Principles and Practice Using C++ (2nd Edition) for people just beginning to learn to program, and A Tour of C++ (2nd Edition) for people who are already programmers and need to know about modern C++. People with a strong mathematical background can start with Peter Gottschling‘s Discovering Modern C++: An Intensive Course for Scientists, Engineers, and Programmers. Once you start using C++ for real, you need a set of guidelines to distinguish what can be done and what is good practice. For that, I recommend the C++ Core Guidelines on GitHub. For good brief explanations of individual language features and standard-library functions, I recommend www.cppreference.com.
#4. What are the differences between a pointer variable and a reference variable in C++?

Both are represented in memory as a machine address. The difference is in their use. To initialize a pointer, you give it the address of an object:
int x = 7; int* p1 = &x; int* p2 = new int;
To read and write through a pointer, we use the dereference operator (*):
*p1 = 9; // write through p1 int y = *p2; // read through p2
When we assign one pointer to another, they will both point to the same object:
p1 = p2; // now p1 p2 both point to the int with the value 9 *p2 = 99; // write 99 through p2 int z = *p1; // reading through p1, z becomes 99 (not 9)
Note that a pointer can point to different objects during its lifetime. That’s a major difference from references. A reference is bound to an object when it is created and cannot be made to refer to another. For references, dereferencing is implicit. You initialize a reference with an object and the reference takes its address.
int x = 7; int& r1 = x; int& r2 = *new int;
Operator new returns a pointer, so I had to dereference it before assigning using it to initialize the reference. To read and write through a reference, we just use the reference’s name (no explicit dereferencing):
r1 = 9; // write through r1 int y = r2; // read through r2
When we assign one reference to another, the value referred to will be copied:
r1 = r2; // now p1 and p2 both have the value 9 r1 = 99; // write 99 through r1 int z = r2; // reading through r2, z becomes 9 (not 99)
Both references and pointers are frequently used as function arguments:
void f(int* p) < if (p == nullptr) return; // . >void g(int& r) < // . >int x = 7; f(&x); g(x);
A pointer can be the nullptr, so we have to consider whether it points to anything. A reference can be assumed to refer to something.
#5. How do I iterate over the words of a string?

Use a stringstream, but how do you define “a word”? Consider “Mary had a little lamb.” Is the last word “lamb” or “lamb.”? If there is no punctuation, it is easy:
vector split(const string& s) < stringstream ss(s); vectorwords; for (string w; ss>>w; ) words.push_back(w); return words; > auto words = split("here is a simple example"); // five words for (auto& w : words) cout
for (auto& w : split("here is a simple example")) cout
By default, the >> operator skips whitespace. If we want arbitrary sets of delimiters, things get a bit more messy:
template string get_word(istream& ss, Delim d) < string word; for (char ch; ss.get(ch); ) // skip delimiters if (!d(ch)) < word.push_back(ch); break; >for (char ch; ss.get(ch); ) // collect word if (!d(ch)) word.push_back(ch); else break; return word; >
The d is an operation telling whether a character is a delimiter and I return "" (the empty string) to indicate that there wasn’t a word to return.
vector split(const string& s, const string& delim) < stringstream ss(s); auto del = [&](char ch) < for (auto x : delim) if (x == ch) return true; return false; >; vector words; for (string w; (w = get_word(ss, del))!= ""; ) words.push_back(w); return words; > auto words = split("Now! Here is something different; or is it? ", ". ;? "); for (auto& w : words) cout
If you have the C++20 Range library, you don’t have to write something like this yourself but can use a split_view.
Bjarne Stroustrup is a Technical Fellow and Managing Director at Morgan Stanley in New York City and a Visiting Professor at Columbia University. He's also the creator of C++. For more information on C++20: https://isocpp.org.
Done reading this awesome post? We have something fun for ya. The Stack Overflow podcast is back! Come check it out or listen below.