gpt4 book ai didi

c - 字符串/字符 * 连接,C

转载 作者:行者123 更新时间:2023-11-30 20:36:10 26 4
gpt4 key购买 nike

我尝试打开一个文件(Myfile.txt)并将每一行连接到一个缓冲区,但得到了意外的输出。问题是,我的缓冲区没有更新最后连接的行。我的代码中缺少什么吗?

Myfile.txt(要打开和读取的文件)

Good morning line-001:
Good morning line-002:
Good morning line-003:
Good morning line-004:
Good morning line-005:
.
.
.

Mycode.c

#include <stdio.h>
#include <string.h>

int main(int argc, const char * argv[])
{
/* Define a temporary variable */
char Mybuff[100]; // (i dont want to fix this size, any option?)
char *line = NULL;
size_t len=0;
FILE *fp;
fp =fopen("Myfile.txt","r");
if(fp==NULL)
{
printf("the file couldn't exist\n");
return;
}
while (getline(&line, &len, fp) != -1 )
{
//Any function to concatinate the strings, here the "line"
strcat(Mybuff,line);
}
fclose(fp);
printf("Mybuff is: [%s]\n", Mybuff);

return 0;
}

我期望我的输出是:

Mybuff is: [Good morning line-001:Good morning line-002:Good morning line-003:Good morning line-004:Good morning line-005:]

但是,我遇到了段错误(运行时错误)和垃圾值。有想做什么吗?谢谢。

最佳答案

指定MyBuff为指针,并使用动态内存分配。

#include <stdlib.h>    /*  for dynamic memory allocation functions */

char *MyBuff = calloc(1,1); /* allocate one character, initialised to zero */
size_t length = 1;

while (getline(&line, &len, fp) != -1 )
{
size_t newlength = length + strlen(line)
char *temp = realloc(MyBuff, newlength);
if (temp == NULL)
{
/* Allocation failed. Have a tantrum or take recovery action */
}
else
{
MyBuff = temp;
length = newlength;
strcat(MyBuff, temp);
}
}

/* Do whatever is needed with MyBuff */

free(MyBuff);

/* Also, don't forget to release memory allocated by getline() */

上面的代码将为 getline() 读取的每一行在 MyBuff 中留下换行符。我将把删除它们作为练习。

注意:getline()是linux,而不是标准C。标准C中可以使用像fgets()这样的函数来从文件中读取行,尽管它不不像 getline() 那样分配内存。

关于c - 字符串/字符 * 连接,C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36675453/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com