c - 在 C 中构建一个字符串。我做对了吗?

标签 c

不久前我问过this question .

我最终找到了一种解决方案:

int convertWindowsSIDToString(void *sidToConvert, int size, char* result) {
    const char *sidStringPrefix = "S-";
    int i;
    int concatLength = 0;
    /* For Linux I have SID defined in a seperate header */
    SID *sid;   
    char revision[2], identifierAuthority[2];

    if(sidToConvert == NULL) {
        return 1;
    }

    sid = (SID *)sidToConvert;  

    snprintf(revision, 2, "%d", sid -> Revision);
    snprintf(identifierAuthority, 2, "%d", sid -> IdentifierAuthority.Value[5]);

    /* Push prefix in to result buffer */
    strcpy (result,sidStringPrefix);
    /* Add revision so now should be S-{revision} */
    strcat(result, revision);
    /* Append another - symbol */
    strcat(result, "-");
    /* Add the identifier authority */
    strcat(result, identifierAuthority);


    /* Sub Authorities are all stored as unsigned long so a little conversion is required */
    for (i = 0; i < sid -> SubAuthorityCount; i++) {
        if(concatLength > 0){
            concatLength += snprintf(result + concatLength, size, "-%lu", sid -> SubAuthority[i]);
        } else {
            concatLength = snprintf(result, size, "%s-%lu", result, sid -> SubAuthority[i]);
        }
    }

    return 0;
}

我完全是 C 语言的业余爱好者。 在我运行的几个测试用例中,这工作正常,但我担心我在这里处理字符串的方式。

在这种情况下有没有更好的方法来处理字符串连接?请注意,我在某种程度上与 C89 兼容性有关,因为我试图让所有代码在所有平台上编译,并且目前在 Windows 上使用 Visual Studio。

如果这个问题不是 Stack Overflow 的最佳格式,我也深表歉意。我想我要求更多的代码审查是一个非常具体的问题,但不确定还能去哪里。

编辑

只是想根据此处的建议添加我认为几乎是最终解决方案,然后再接受答案。

int convertWindowsSIDToString(SID *sidToConvert, int size, char* result) {
    int i;  
    char* t;    
    if(sidToConvert == NULL) {
        printf("Error: SID to convert is null.\n");
        return 1;
    }   
    if(size < 32) {
        printf("Error: Buffer size must be at least 32.\n");
        return 1;
    }
    t = result;
    t+= snprintf(t,  size, "S-%d-%d", sidToConvert->Revision, sidToConvert->IdentifierAuthority.Value[5]);

    for (i = 0; i < sidToConvert -> SubAuthorityCount; i++) {
        t += snprintf(t, size - strlen(result), "-%lu", sidToConvert -> SubAuthority[i]);
    }

    return 0;
}

从表面上看,我还有很多书要读。不得不承认,C 非常有趣。

最佳答案

如果您知道结果缓冲区将足够 bin(您通常可以通过为任何格式分配所需的最大空间并在格式化之前验证您的输入来确保这一点),您可以执行以下操作:

char* buffer = malloc(BIG_ENOUGH);
char* t = buffer;
t+=sprintf(t, "%d", sid->Revision);
t+=sprintf(t, "%d", sid->IdentifierAuthority.Value[5]);
for (i = 0; i < sid -> SubAuthorityCount; i++) {
    t += sprintf(t, "-%lu", sid -> SubAuthority[i]);
}
printf("Result: %s\n", buffer);

关于c - 在 C 中构建一个字符串。我做对了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21307428/

相关文章:

c++ - 使用表达式初始化数组

c - 调整结构中的内存对齐

c - 线程函数 sum_array() 无法被 main 函数调用

c - 使用 MPI Send/Recv 实现自己的矩阵乘法

c++ - 在 cpp 项目 (VS2005) 中编译的 c 模块中无法识别内联关键字

c - GtkTreeView 在 GtkBox 中时不显示所有行

c - 使用存储在 C 结构中的变量引用结构的成员

c++ - C hack 用于存储占用 1 位空间的位?

c - 字符串末尾的空字符 '\0'

c - 评分网站一直说我的代码超出了时间限制