【发布时间】: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