i have a big problem and i dont know how to fix it…
I want to decode a very long Base64 encoded string (980.000 Chars) but every time when i to debug it i get this error :
Error C2026: string too big, trailing characters truntraced
I tried this but i can only compare 2 strings throught this method
char* toHash1 = "LONG BASE 64 Code";
char* toHash2 = "LONG BASE 64 Code";
if (true) {
sprintf_s(output, outputSize, "%s", base64_decode(toHash1 =+ toHash2).c_str());
}
Anyone know how i can get it to work?
asked Apr 30, 2015 at 11:26
1
As documented here, you can only have about 2048 characters in a string literal when using MSVC. You can get up to 65535 characters by concatenation, but since this is still too short, you cannot use string literals here.
One solution would be reading the string from a file into some allocated char
buffer. I do not know of any such limits for gcc and clang, so trying to use them instead of MSVC could solve this too.
answered Apr 30, 2015 at 13:34
Baum mit Augen♦Baum mit Augen
48.6k24 gold badges144 silver badges179 bronze badges
1
You can first convert your string to hex and then can include it like this,
char data[] = {0xde,0xad,0xbe,0xef}; //example
And than can use it like a string, append null terminator if needed to.
answered Aug 21, 2016 at 0:46
Alok SainiAlok Saini
3216 silver badges18 bronze badges
Как создать длинные константные строки в исходном файле?
, имеется большой текстовый файл, как его вставить в исходник?
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
Junior Рейтинг (т): нет |
Здраствуйте!
CHAR strFile[] = «sfsdfsdfsdf gdfgdfgdfg rtertertertertterterttertertrwerwerwtrwetSASDGDfg»; но компилятор ругается: «error C2026: string too big, trailing characters truncated» Сообщение отредактировано: VictorRT — 05.02.09, 10:14 |
trainer |
|
Как обычно
CHAR strFile[] = «sfsdfsdfsdf» «gdfgdfgdfg» «rtertertertertterterttertertrwerwerwtrwetSASDGDfg»; P.S. Вот насчет 100000 символов — сильно не уверен. Сообщение отредактировано: trainer — 05.02.09, 10:04 |
Relaxander |
|
CHAR strFile[] = «sfsdfsdfsdf» |
VictorRT |
|
Junior Рейтинг (т): нет |
Цитата Relaxander @ 05.02.09, 10:03 CHAR strFile[] = «sfsdfsdfsdf» окей, щас попробуем этот вариант! Добавлено 05.02.09, 10:30
CHAR strFile[] = «sfsdfsdfsdf» «gdfgdfgdfg» «rtertertertert\tertert\tertert\rwerwerwtrwetSASDGDfg\»;
то при относительно небольшой длине всё работает, а при большой длине выдается ошибка: Сообщение отредактировано: VictorRT — 05.02.09, 10:32 |
Мяут |
|
VictorRT, Relaxander бред говорит — используйте вариант trainer’а Добавлено 05.02.09, 10:32 Цитата VictorRT @ 05.02.09, 10:15 а большой длине выдается ошибка: Что естественно, учитывая, что размер сегмента в x86 — 64K |
Relaxander |
|
Цитата Мяут @ 05.02.09, 10:31 VictorRT, Relaxander бред говорит доказательства? |
ЫукпШ |
|
Цитата VictorRT @ 05.02.09, 09:54 Пытался делать так:
CHAR strFile[] = «sfsdfsdfsdf gdfgdfgdfg rtertertertertterterttertertrwerwerwtrwetSASDGDfg»; но компилятор ругается: «error C2026: string too big, trailing characters truncated» Попробуй так:
CHAR strFile[] = «sfsdfsdfsdf gdfgdfgdfg rtertertertert\tertert\tertert\rwerwerwtrwetSASDGDfg\»; -Added 05.02.09, 11:01 Цитата VictorRT @ 05.02.09, 09:54 Проблема заключается в следующем: Напрашивается вариант :»Вставить этот файл в ресурсы». Еще интереснее — упаковать zip-ом, вставить в ресурсы, Сообщение отредактировано: ЫукпШ — 05.02.09, 11:02 |
VictorRT |
|
Junior Рейтинг (т): нет |
to ЫукпШ: спасибо, интересная идея! Сам стал к этому склоняться ) |
KILLER |
|
Цитата VictorRT @ 05.02.09, 09:54 Подскажите пожалуйста, кто знает, как создать длинную константную тектовую строку в исходном файле?
Именно для этого и были придуманы динамические массивы |
miksayer |
|
Цитата KILLER @ 05.02.09, 11:37 Именно для этого и были придуманы динамические массивы а вдруг топикстартеру нужно, чтобы простой смертный не смог изменить этот файл? |
KILLER |
|
Цитата miksayer @ 05.02.09, 11:45 а вдруг топикстартеру нужно, чтобы простой смертный не смог изменить этот файл?
Тогда пусть юзает шифрование, и кстати при компиляции текст строковых массивов остаеться как и был, т.е. не компилируеться ин е шифруеться, можно фаром открыть *.ехе файл и втупую изменить его, главное не увиличить длинну массива. |
pan2004 |
|
Senior Member Рейтинг (т): 63 |
VictorRT, если есть Qt, прогони свой файл через утилиту uic. Она тебе C++ный массив сделает) |
VictorRT |
|
Junior Рейтинг (т): нет |
Всем спасибо! Я выбрал вариант с хранением файла в ресурсах! |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- C/C++: Общие вопросы
- Следующая тема
[ Script execution time: 0,0521 ] [ 16 queries used ] [ Generated: 9.02.23, 12:11 GMT ]
Максимальная длина CString
От: |
peer |
||
Дата: | 22.05.06 12:37 | ||
Оценка: |
мне нужно задать статический массив CString
и почему-то пишет error C2026: string too big, trailing characters truncated на строку длиной 1000 символов.
Хотя при динам.считывании считывает 4000 символов в CString спокойно. Может есть какие-то ограничения?
Подскажите как обойти проблемы чтобы можно было делать стат.строки большого размера, желательно не char/
Re: Максимальная длина CString
От: |
_DAle_
|
||
Дата: | 22.05.06 12:40 | ||
Оценка: |
Здравствуйте, peer, Вы писали:
P>мне нужно задать статический массив CString
P>и почему-то пишет error C2026: string too big, trailing characters truncated на строку длиной 1000 символов.
P>Хотя при динам.считывании считывает 4000 символов в CString спокойно. Может есть какие-то ограничения?
P>Подскажите как обойти проблемы чтобы можно было делать стат.строки большого размера, желательно не char/
CString str = «verylongstringverylongstringverylongstringverylongstringverylongstringverylongstring»
«verylongstringverylongstringverylongstringverylongstringverylongstringverylongstring»
«verylongstringverylongstringverylongstringverylongstringverylongstringverylongstring»;
подойдет?
Re: Максимальная длина CString
От: |
kan_izh
|
||
Дата: | 22.05.06 12:46 | ||
Оценка: |
peer wrote:
> мне нужно задать статический массив CString
> и почему-то пишет error C2026: string too big, trailing characters
открываем msdn, вводим C2026, читаем:
Posted via RSDN NNTP Server 2.0
но это не зря, хотя, может быть, невзначай
гÅрмония мира не знает границ — сейчас мы будем пить чай
Re[2]: Максимальная длина CString
От: |
kan_izh
|
||
Дата: | 22.05.06 12:47 | ||
Оценка: |
kan_izh wrote:
>> мне нужно задать статический массив CString
>> и почему-то пишет error C2026: string too big, trailing characters
> открываем msdn, вводим C2026, читаем:
Error Message
string too big, trailing characters truncatedThe string was longer than the limit of 16380 single-byte characters.
Prior to adjacent strings being concatenated, a string cannot be longer than 16380 single-byte characters.
A Unicode string of about one half this length would also generate this error.
If you have a string defined as follows, it generates C2026:
Copy Code
char sz[] =
«
imagine a really, really
long string here
«;You could break it up as follows:
Copy Code
char sz[] =
«
imagine a really, really «
«long string here
«;You may want to store exceptionally large string literals (32K or more) in a custom resource or an external file. See
Creating a New Custom or Data Resource for more information.
Posted via RSDN NNTP Server 2.0
но это не зря, хотя, может быть, невзначай
гÅрмония мира не знает границ — сейчас мы будем пить чай
Re[2]: Максимальная длина CString
От: |
peer |
||
Дата: | 22.05.06 13:03 | ||
Оценка: |
Здравствуйте, _DAle_, Вы писали:
_DA>Здравствуйте, peer, Вы писали:
P>>мне нужно задать статический массив CString
P>>и почему-то пишет error C2026: string too big, trailing characters truncated на строку длиной 1000 символов.
P>>Хотя при динам.считывании считывает 4000 символов в CString спокойно. Может есть какие-то ограничения?
P>>Подскажите как обойти проблемы чтобы можно было делать стат.строки большого размера, желательно не char/
_DA>CString str = «verylongstringverylongstringverylongstringverylongstringverylongstringverylongstring»
_DA> «verylongstringverylongstringverylongstringverylongstringverylongstringverylongstring»
_DA> «verylongstringverylongstringverylongstringverylongstringverylongstringverylongstring»;
_DA>подойдет?
Да супер! работает.Спасибо!
- Переместить
- Удалить
- Выделить ветку
Пока на собственное сообщение не было ответов, его можно удалить.
You must Sign In to use this message board. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
У меня большая проблема, и я не знаю, как ее исправить …
Я хочу декодировать очень длинную строку в кодировке Base64 (980.000 символов), но каждый раз, когда я отлаживаю ее, я получаю эту ошибку:
Ошибка C2026: слишком большая строка, конечные символы передаются
Я пытался это, но я могу сравнить только 2 строки через этот метод
char* toHash1 = "LONG BASE 64 Code";
char* toHash2 = "LONG BASE 64 Code";
if (true) {
sprintf_s(output, outputSize, "%s", base64_decode(toHash1 =+ toHash2).c_str());
}
Кто-нибудь знает, как я могу заставить его работать?
1
Решение
Как задокументировано Вот, вы можете иметь только около 2048 символов в строковом литерале при использовании MSVC. Вы можете получить до 65535 символов путем конкатенации, но поскольку это все еще слишком мало, вы не можете использовать строковые литералы здесь.
Одним из решений было бы чтение строки из файла в некоторый выделенный char
буфер. Я не знаю каких-либо таких ограничений для gcc и clang, поэтому попытка использовать их вместо MSVC также может решить эту проблему.
3
Другие решения
Вы можете сначала преобразовать свою строку в шестнадцатеричный формат, а затем включить его следующим образом:
char data[] = {0xde,0xad,0xbe,0xef}; //example
И чем можно использовать его как строку, добавьте нулевой терминатор, если необходимо.
1
Very often we need to include into our programs some resources like textures, sounds, static data etc. Usually, we distribute them with the programs as files. However, if you want to distribute the application as a single executable, it may become a bit tricky.
Classical approach for GCC
The most elegant way to do it, was described here. It works perfectly but only on Linux with GCC.
Portable approach
If you want a portable approach for including your resources,
you can use cmake
and generate a header file with the resources as strings.
Let’s create a template with name resource.h.in
:
#ifndef RESOURCE_H
#define RESOURCE_H
#include <string_view>
namespace app {
static std::string_view kResource = "@RESOURCE_DATA@";
}
#endif // RESOURCE_H
Enter fullscreen mode
Exit fullscreen mode
In your CMakeLists.txt
you should read the resource from its file and use configure_file
to generate a header:
file(READ ${CMAKE_CURRENT_BINARY_DIR}/path/to/resource.data RESOURCE_DATA HEX)
configure_file(resource.h.in ${CMAKE_BINARY_DIR}/app/resource.h @ONLY)
Enter fullscreen mode
Exit fullscreen mode
We need to represent our data as hex-digits, overwise your binary data breaks the C++ strings. It isn’t a big deal, you can later convert it into a normal string in your C++ code:
auto hex_str_to_str = [](std::string hex) {
auto len = hex.length();
std::transform(hex.begin(), hex.end(), hex.begin(), toupper);
std::string new_string;
for (int i = 0; i < len; i += 2) {
auto byte = hex.substr(i, 2);
char chr = ((byte[0] - (byte[0] < 'A' ? 0x30 : 0x37)) << 4) + (byte[1] - (byte[1] < 'A' ? 0x30 : 0x37));
new_string.push_back(chr);
}
return new_string;
};
auto data = hex_str_to_str(std::move(hex));
Enter fullscreen mode
Exit fullscreen mode
Unfortunately, if your resources are big, you may meet this error on Windows:
C2026: string too big, trailing characters truncated
Enter fullscreen mode
Exit fullscreen mode
It happens if your string is bigger than 16380 chars.
Annoying… but it’s possible to work around the problem.
We can reformat the strings in Python:
"""Script to reformat long string for Windows"""
import sys
STEP = 16000
if __name__ == "__main__":
filename = sys.argv[1]
split = []
with open(filename, "r") as file:
while True:
chunk = file.read(STEP)
split.append(chunk)
if len(chunk) < STEP:
break
with open(filename, "w") as file:
file.write('"n"'.join(split))
Enter fullscreen mode
Exit fullscreen mode
and run it in our CMakeLists.txt
:
file(READ ${CMAKE_CURRENT_BINARY_DIR}/path/to/resource.data RESOURCE_DATA HEX)
configure_file(resource.h.in ${CMAKE_BINARY_DIR}/app/resource.h @ONLY)
execute_process(COMMAND python3 ${CMAKE_SOURCE_DIR}/cmake/split_string.py ${CMAKE_BINARY_DIR}/app/resource.h)
Enter fullscreen mode
Exit fullscreen mode
Of course, you need Python on your machine now. If it is an issue, you can find out how to do it in pure-CMake as well.
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
Hi All,
I am trying to compile a buildop and i face this problem,
##E TBLD 000000 Subprocess command failed with exit status 512
##I TBLD 000008 cxx -O -IC:/Ascential/DataStage/Projects/ROCKVILLE/buildop -IC:/Ascential/DataStage/PXEngine/include -W/TP -W/EHa -DAPT_USE_ANSI_IOSTREAMS -c C:/Ascential/DataStage/Projects/ROCKVILLE/buildop/bosource2296-0.C -o C:/Ascential/TMP/bosource2296-0_s.o
##I TBLD 000000 Output from subprocess: bosource2296-0.C(336) : error C2026: string too big, trailing characters truncated
This problem is related to the output schema/table of the buildop. Here is the schema,
record
{final_delim=end, record_delim_string=’rn’, delim=’,’, quote=double}
(
COMPANY_CD:string[max=10];
FISCAL_YR:string[4];
QUARTER_FLG:string[1];
RESTATE_FLG:string[1];
FIN_A_DATE:string[max=8] {null_field=»};
ASST_CH_CASH:string[max=16] {quote=none, null_field=»};
ASST_MS_MRKT_SECURTY:string[max=16] {quote=none, null_field=»};
ASST_RE_RECEIVABLES:string[max=16] {quote=none, null_field=»};
ASST_IV_INVENTORIES:string[max=16] {quote=none, null_field=»};
ASST_RM_RAW_MAT:string[max=16] {quote=none, null_field=»};
ASST_WP_WRK_IN_PRGRS:string[max=16] {quote=none, null_field=»};
ASST_FG_FINSHD_GDS:string[max=16] {quote=none, null_field=»};
ASST_NO_NOTES_RCV:string[max=16] {quote=none, null_field=»};
ASST_OC_OTH_CURR_ASST:string[max=16] {quote=none, null_field=»};
ASST_CA_TOT_CURR_ASST:string[max=16] {quote=none, null_field=»};
ASST_PR_PROP_PLT_EQT:string[max=16] {quote=none, null_field=»};
ASST_DR_ACC_DEP:string[max=16] {quote=none, null_field=»};
ASST_PN_NET_PROP_EQT:string[max=16] {quote=none, null_field=»};
ASST_VV_INVS_ADV:string[max=16] {quote=none, null_field=»};
ASST_TH_OTH_NON_CUR_ASST:string[max=16] {quote=none, null_field=»};
ASST_CD_DEF_CHRG:string[max=16] {quote=none, null_field=»};
ASST_IG_INSTANGIBLE:string[max=16] {quote=none, null_field=»};
ASST_DA_DEP_OTH_ASST:string[max=16] {quote=none, null_field=»};
ASST_AS_TOT_ASST:string[max=16] {quote=none, null_field=»};
LIAB_NT_NOTE_PAY:string[max=16] {quote=none, null_field=»};
LIAB_AP_ACC_PAY:string[max=16] {quote=none, null_field=»};
LIAB_L2_CURR_LONG_TERM_DEBT:string[max=16] {quote=none, null_field=»};
LIAB_L3_CURR_PORT_CAP:string[max=16] {quote=none, null_field=»};
LIAB_L4_ACCR_EXPENSE:string[max=16] {quote=none, null_field=»};
LIAB_TX_INCOME_TAX:string[max=16] {quote=none, null_field=»};
LIAB_LL_OTH_CURR_LIAB:string[max=16] {quote=none, null_field=»};
LIAB_TC_TOT_CURR_LIAB:string[max=16] {quote=none, null_field=»};
LIAB_L5_MORTAGE:string[max=16] {quote=none, null_field=»};
LIAB_L6_DEFF_CHRG_INC:string[max=16] {quote=none, null_field=»};
LIAB_L7_CONVERTIBLE_DEBT:string[max=16] {quote=none, null_field=»};
LIAB_LD_LONG_TERM_DEBT:string[max=16] {quote=none, null_field=»};
LIAB_L8_NON_CUR_CAP_LEASE:string[max=16] {quote=none, null_field=»};
LIAB_OL_OTH_LONG_TERM_LIAB:string[max=16] {quote=none, null_field=»};
LIAB_L9_TOT_LIAB:string[max=16] {quote=none, null_field=»};
LIAB_MI_MINORITY_INT:string[max=16] {quote=none, null_field=»};
LIAB_LC_PREF_STK:string[max=16] {quote=none, null_field=»};
LIAB_LA_COMM_STK_NET:string[max=16] {quote=none, null_field=»};
LIAB_LB_CAP_SURPLUS:string[max=16] {quote=none, null_field=»};
LIAB_OE_RET_EARNING:string[max=16] {quote=none, null_field=»};
LIAB_TS_TREASURY_STK:string[max=16] {quote=none, null_field=»};
LIAB_LO_OTH_LIAB:string[max=16] {quote=none, null_field=»};
LIAB_NW_SHR_EQUITY:string[max=16] {quote=none, null_field=»};
LIAB_LE_TOT_LIAB_NET_WORTH:string[max=16] {quote=none, null_field=»};
INST_DS_OUT_CMN_STK:string[max=16] {quote=none, null_field=»};
INST_SA_NET_SALES:string[max=16] {quote=none, null_field=»};
INST_CG_COST_OF_GOOD:string[max=16] {quote=none, null_field=»};
INST_GP_GROSS_PROFIT:string[max=16] {quote=none, null_field=»};
INST_I1_R_D_EXP:string[max=16] {quote=none, null_field=»};
INST_SG_SELL_GEN_ADM_EXP:string[max=16] {quote=none, null_field=»};
INST_I2_INC_BEF_DEP_AMORT:string[max=16] {quote=none, null_field=»};
INST_I3_DEP_AMORT:string[max=16] {quote=none, null_field=»};
INST_I4_NON_OPER_INC:string[max=16] {quote=none, null_field=»};
INST_I5_INTR_EXP:string[max=16] {quote=none, null_field=»};
INST_PI_INC_BEF_TAX:string[max=16] {quote=none, null_field=»};
INST_TT_PROV_INC_TAX:string[max=16] {quote=none, null_field=»};
INST_I6_MIN_INTEREST:string[max=16] {quote=none, null_field=»};
INST_GL_INV_GAIN_LOSS:string[max=16] {quote=none, null_field=»};
INST_IO_OTH_INC:string[max=16] {quote=none, null_field=»};
INST_I7_NET_INC_BEF_EX:string[max=16] {quote=none, null_field=»};
INST_EI_EX_DISC_OPS:string[max=16] {quote=none, null_field=»};
INST_IN_NET_INC:string[max=16] {quote=none, null_field=»};
)
When i remove the last few columns from the schema(around 15 columns) i dont get this error, i can understand this is a C++ compiler issue (Errror Code: C2026)
My Environment
—————
Data Stage Engine : 7.5×2
OS : Windows 2000 Server with SP4 with .NET 2003
Could you please share your thoughts on it?
Thanks,
Sidharth