我试图打开一个文件(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 existn");
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()
那样分配内存。