0

我正在使用 NanoPB 将编码数据(数组unsigned char)从服务器发送到客户端。我将每个字节映射为一个char,将它们连接起来,然后通过网络作为一个完整的字符串发送。在客户端,我有一个串行接口,可以使用getcor读取服务器的响应gets。问题是缓冲区可能有null-terminating chars并且gets会失败。例如,假设缓冲区包含如下内容:

unsigned char buffer[] = {72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 0, 24, 1, 32, 1, 40, 0};

为简单起见,我将缓冲区写入文件并尝试将其读回并重建它(借助this):

#include <stdio.h>

void strInput(FILE *fp, char str[], int nchars) {
    int i = 0;
    int ch;
    while ((ch = fgetc(fp)) != '\n' && ch != EOF) {
        if (i < nchars) {
            str[i++] = ch;
        }
    }
    str[i] = '\0';
}

void readChars(FILE *fp)
{
    char c = fgetc(fp);
    while (c != EOF)
    {
        printf("%c", c);
        c = fgetc(fp);
    }
}


int main() {
    FILE *fp;
    const char* filepath = "mybuffer.txt";
    char c;
    char buffer[100];

    fp = fopen(filepath, "r+");    
    strInput(fp, buffer, sizeof(buffer));
    printf("Reading with strInput (WRONG): %s\r\n", buffer);
    fclose(fp);

    fp = fopen(filepath, "r+");
    printf("Reading char by char: ");
    readChars(fp);
    printf("\r\n");
    fclose(fp);

    getchar();
    return 0;
}

这是输出:

Reading with strInput (WRONG): Hello world
Reading char by char: Hello world  (

如何从该文件重建缓冲区?为什么readChars打印所有缓冲区strInput而不打印?

4

1 回答 1

2

“为什么readChars打印所有缓冲区strInput而不打印?”

readChars()函数实际上在函数中打印所有读取的字符,一次一个:

while (c != EOF)
    {
        printf("%c", c);
        c = fgetc(fp);
    }

但是,该函数使用转换说明符strInput()将 的内容打印buffer[]为字符串:%s

strInput(fp, buffer, sizeof(buffer));
printf("Reading with strInput (WRONG): %s\r\n", buffer);

\0这次遇到嵌入字符时打印停止,因为这就是这样%s做的。

请注意,creadChars()函数中应该是一个int,而不是一个char。该fgetc()函数返回一个int值,并且EOF可能无法在char.

如果要查看嵌入的空字节,请buffer[]一次打印一个字符:

#include <stdio.h>

int main(void)
{
    FILE *fp = fopen("mybuffer.txt", "r");  // should check for open failure

    char buffer[100] = { '\0' };  // zero to avoid UB when printing all chars
    fgets(buffer, sizeof buffer, fp);
//  could just as well use:
//  strInput(fp, buffer, sizeof(buffer));

    for (size_t i = 0; i < sizeof buffer; i++) {
        if (buffer[i] == '\0') {
            putchar('*');        // some character not expected in input
        }
        else {
            putchar(buffer[i]);
        }
    }
    putchar('\n');

    return 0;
}
于 2018-12-12T05:50:16.800 回答