我正在尝试将文件中的一行重复 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/