【问题标题】:How to create a custom char in c?如何在 c 中创建自定义字符?
【发布时间】:2022-11-23 05:05:28
【问题描述】:

我必须像这样为 Tftp 客户端创建请求数据报 (RRQ):

但是我不能使用结构,因为字段的长度是可变的。

我尝试了 struct 和一些在 char 上迭代的东西。

【问题讨论】:

  • 你到底在问什么?我的意思是,自然而然的做法似乎是使用 charunsigned char 的数组,而且您似乎已经想到了这一点。什么是挂断?
  • 您将不得不将数据编组到 char 缓冲区中
  • @JohnBollinger 我想做这样的事情:创建一个字符数据报[长度],然后添加操作码(我认为数据报=htons(1)),然后添加第二个字段,然后是 0...
  • @JohnBollinger 我不知道如何将它们一一添加。
  • @TusMuela,sprintf()strcpy()memcpy(),....

标签: c tftp


【解决方案1】:

创建一个字节数组并附加到它。您可以通过使用指针算法来跟踪您所写的位置(有点像游标),从而使这更容易。

我们可以通过跟踪请求内存中存档和模式字符串的起始位置来让我们自己的生活更轻松,以便我们以后可以轻松找到它们。

typedef struct {
    char *archive;
    char *mode;
    char *request;
} Read_Request;

Read_Request *read_request_create(const char *archive, const char *mode) {
    Read_Request *rrq = malloc(sizeof(Read_Request));

    // Allocate sufficient memory for the opcode and both strings,
    // including the terminating nulls.
    rrq->request = malloc(2 + strlen(archive) + 1 + strlen(mode) + 1);

    // Start the request with the opcode.
    memcpy(rrq->request, "01", 2);

    // Put the start of the archive 2 bytes in, just after the opcode.
    rrq->archive = rrq->request + 2;

    // Copy the archive string after the opcode.
    strcpy(rrq->archive, archive);

    // Put the start of the mode just after the archive and its null byte.
    rrq->mode = rrq->archive + strlen(archive) + 1;

    // Append the mode string after the archive string.
    strcpy(rrq->mode, mode);

    return rrq;
}

然后打印很容易。由于 C 字符串在空字节处停止,我们可以简单地打印存档和模式字符串。

void read_request_print(Read_Request *rrq) {
    // Print the opcode at the start of the request.
    printf("opcode: ");
    fwrite(rrq->request, 1, 2, stdout);
    puts("");

    // Print the archive and modes.
    printf("archive: '%s'
", rrq->archive);
    printf("mode: '%s'
", rrq->mode);
}

int main() {
    Read_Request *rrq = read_request_create("archive", "mode");

    read_request_print(rrq);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    • 2016-02-14
    • 2011-11-18
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多