-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:]
しかし、セグメンテーションフォルト(実行時エラー)とガベージ値を取得しています。どのようなことをすると思いますか?ありがとう。
ハードコーディングされた制限は100です。ポインタを使用してください。*ヒント:realloc * – t0mm13b
@ t0mm13b:リプレイに感謝しますが、同じ問題があります。追加されたMybuff = realloc(Mybuff、sizeof mybuff)、...あなたは私を助けてくれますか? –
[このコーネル講義ノート](http://www.cs.cornell.edu/courses/cs2022/2011sp/lectures/lect04.pdf)を読む! K&Rの本も入手してください。そこから始める。 – t0mm13b