String / char * concatinate,C

时间:2016-04-17 10:39:29

标签: c malloc concatenation strcat

我试图打开一个文件(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:]

但是,我得到了分段错误(运行时错误)和垃圾值。有想过吗?感谢。

1 个答案:

答案 0 :(得分:0)

指定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() */

以上内容会为MyBuff读取的每一行getline()留下换行符。我会把这些作为练习去除。

注意:getline()是linux,而不是标准C.标准C中有fgets()这样的函数可用于从文件中读取行,尽管它不会像{{1一样分配内存确实。