【问题标题】:String / char * concatinate, C字符串 / char * 连接,C
【发布时间】:2016-04-17 10:39:28
【问题描述】:

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

但是,出现分段错误(运行时错误)和垃圾值。有什么想做的吗?谢谢。

【问题讨论】:

  • 您遇到缓冲区溢出,硬编码限制为 100。使用指针,hint: realloc
  • @t0mm13b:感谢您的重播,但还是同样的问题!添加了 Mybuff = realloc(Mybuff, sizeof mybuff), ...你能帮我吗,我是 C 语言的新手。
  • 先阅读this Cornell lecture notes!获取 K&R 书。从那里开始。
  • K&R 太旧了,不能再使用了。人们应该忘记曾经存在过。

标签: c malloc concatenation strcat


【解决方案1】:

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。像 fgets() 这样的函数可以在标准 C 中用于从文件中读取行,尽管它不像 getline() 那样分配内存。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 2013-08-30
    • 2013-10-31
    相关资源
    最近更新 更多