输入字符串包含空终止字符

时间:2018-12-12 04:57:13

标签: c nanopb

我正在使用NanoPB从服务器向客户端发送编码数据(unsigned char的数组)。我将每个字节映射为单个char,将它们连接起来,然后通过网络作为一个整体字符串发送。在客户端,我有一个串行接口,可以使用getcgets读取服务器的响应。问题是缓冲区可能有null终止char,而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

1 个答案:

答案 0 :(得分:2)

“为什么 @forelse( $vehicles as $vehicule ) <td> @if( $vehicule->uploads->count() > 0 ) <a href="{{ route('vehicles.show', $vehicule->id) }}"> @php $upload = $vehicule->uploads->sortByDesc('id')->first(); @endphp <img src="/images/{{ $upload->resized_name }}" ></a> </a> @else This vehicule does not have any images attached. <!-- <img src="/images/{{'noimage.png'}}"> --> @endif </td> @empty <td>No vehicules to display.</td> @endforelse 打印所有缓冲区,而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函数中的c应该是readChars(),而不是intchar函数返回一个fgetc()值,并且int可能无法在EOF中表示。

如果要查看嵌入的空字节,则一次打印char中的字符:

buffer[]