开发者

Display special characters in C

I have an requirement where the C code extract string data from database and write it to a file. The string data in the database can have any kind of characters

for exam开发者_开发知识库ple: Description field have data "Adj \342\200\223 Data" , when I write to the file the text it writes as "Adj â Data". Similarly, this description field can have any kind of data, my code just read and uses strcpy after extracting from the database and write to a file.

How do I get the data written to a file as it is in the description field ?


Think easiest solution would be writing byte by byte - shouldn't matter that much with buffering:

int pos = 0;
FILE *fp = 0;
//...
fp = fopen("somefile.txt", "w");
//...
while(buffer[pos])
    if(buffer[pos] < 32 || buffer[pos] > 127) // change bounds for non-printable chars as you like
        fprintf(fp, "%c", buffer[pos++]);
    else
        fprintf(fp, "\\%u", buffer[pos++]);

Edit: Might have misunderstood your question. Only use string functions when you're actually working with strings. For binary data use binary functions (e.g. the mentioned memcpy()).

Edit 2/3: Don't print the value as "%d" or "%u" - should be "%3o" to print as a 3-digit octal number. Using "%o" could be unsafe if other digits follow.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜