c - 如何重复将文本 append 到 C 中的字符串?

标签 c append repeat strcat

我正在尝试将文件中的一行重复 append 到名为 lines 的字符串中。当我尝试打印这些行时,我的代码工作正常,但由于我必须解析信息,所以我需要存储它。

int main(int argc, char *argv[])
{
    // Check for arguments and file pointer omitted
    FILE *f = fopen(argv[1], "r");
    char *times;
    int i = 0;

    for (i = 0; i < 2000; i++)
    {
        char line[80];
        if (fgets(line, 80, f) == NULL)
            break;

        //I want every line with the text "</time> to be added to string times
        if(strstr(line, "</time>"))
        {
            times = strcat(times, line);  //This line is my problem
        }
    }

    printf(times);

    fclose(f);
    return 0;
}

最佳答案

您的代码不起作用,因为您需要为字符串分配空间。您将 items 声明为 char 指针,但您没有使其指向有效内存,然后 strcat() 尝试写入它导致未定义的行为。

试试这个

char items[1024];

 items[0] = '\0';

items[0] = '\0'; 是因为 strcat() 会搜索 '\0' 字节第一个字符串并将第二个字符串 append 到第二个字符串的末尾。

您应该注意,如果要连接在一起的字符串太长而无法容纳 items,那么问题会再次发生。

在这种情况下,您要么需要使用 malloc()/realloc() 动态分配空间,要么计算结果字符串的总长度,然后分配足够的空间

关于c - 如何重复将文本 append 到 C 中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30043605/

相关文章:

PHP:找到常见的重复字符串?

c++ - 奇怪的 GCC 优化错误

c - 使用 C 在 Mint 中打开具有目录名称的文件

c - C 中的 While 循环错误

jquery - 如何在jquery中选择最近添加的元素?

Javascript - 将返回的 call_id append 到按钮

javascript - 如何将背景动画制作成循环(重复功能)

内核终端中的光标

javascript - 如何使用 cordova-plugin-file append 到文件

python - 重复数组n次