由于您不使用原始 ANSI 字符串,因此您不能使用旨在用于原始 ANSI 字符串的函数,因为解释字符串的方式。
在 C(和 C++)中,字符串通常以 null 结尾,即最后一个字符是 \0(值 0x00)。至少对于字符串操作和输入/输出的标准函数是这样的(比如printf() 或strcpy())。
例如行
const char *text = "Hello World";
幕后变成
const char *text = "Hello World\0";
因此,当您从文件中读取 \0 并将其放入您的字符串时,您基本上会得到一个基本上为空的字符串。
为了让问题更清楚,只是一个简单的例子:
// Let's just assume the sequence 0x00, 0x01 is some special encoding
const char *input = "Hello\0\1World!";
char output[256];
strcpy(output, input);
// strncpy() is for string manipulation, as such it will stop once it encounters a null terminator
printf("%s\n", output); // This will print 'Hello'
memcpy(output, input, 14); // 14 is the string length above plus null terminator
printf("%s\n", output); // This will again print 'Hello' (since it stops at the terminator)
printf("%s\n", output + 7); // This will print "World" (you're skipping the terminator using the offset)
以下是我整理的一个简单示例。它不一定展示最佳实践,也可能存在一些错误,但它应该向您展示一些可能的概念,如何处理原始字节数据,尽可能避免使用标准字符串函数。
#include <stdio.h>
#define WIDTH 16
int main (int argc, char **argv) {
int offset = 0;
FILE *fp;
int byte;
char buffer[WIDTH] = ""; // This buffer will store the data read, essentially concatenating it
if (argc < 2)
return 1;
if (fp = fopen(argv[1], "rb")) {
for(;;) {
byte = fgetc(fp); // get the next byte
if (byte == EOF) { // did we read over the end of the file?
if (offset % WIDTH)
printf("%*s %*.*s", 3 * (WIDTH - offset % WIDTH), "", offset % WIDTH, offset % WIDTH, buffer);
else
printf("\n");
return 0;
}
if (offset % WIDTH == 0) { // should we print the offset?
if (offset)
printf(" %*.*s", WIDTH, WIDTH, buffer); // print the char representation of the last line
printf("\n0x%08x", offset);
}
// print the hex representation of the current byte
printf(" %02x", byte);
// add printable characters to our buffer
if (byte >= ' ')
buffer[offset % WIDTH] = byte;
else
buffer[offset % WIDTH] = '.';
// move the offset
++offset;
}
fclose(fp);
}
return 0;
}
编译后,将任何文件作为第一个参数传递以查看其内容(不应太大以免破坏格式)。