2016-04-17 7 views
-2

ファイル(Myfile.txt)を開き、各行を単一のバッファに連結しようとしていますが、予期しない出力が発生しています。問題は、私のバッファが最後に連結された行で更新されていないことです。私のコードに欠けているものはありますか?String/char * concatinate、C

の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

ハードコーディングされた制限は100です。ポインタを使用してください。*ヒント:realloc * – t0mm13b

+0

@ t0mm13b:リプレイに感謝しますが、同じ問題があります。追加されたMybuff = realloc(Mybuff、sizeof mybuff)、...あなたは私を助けてくれますか? –

+0

[このコーネル講義ノート](http://www.cs.cornell.edu/courses/cs2022/2011sp/lectures/lect04.pdf)を読む! K&Rの本も入手してください。そこから始める。 – t0mm13b

答えて

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

以上がgetline()によって読み取らライン毎MyBuffに改行を残します。私はそれらを運動として取り除いておきます。

getline()は、Linuxであり、標準ではないC. getline()がないように、メモリを割り当てないにもかかわらずfgets()ような関数は、ファイルから行を読み取るための標準的なC言語で利用可能です。