这是我在这里提问的第一个问题,如果我没有遵循格式规则,请原谅。我正在用C语言编写一个程序,需要从文件中读取几行。我试图将每一行放入一个cstring中。我声明了一个名为buf的二维字符数组,用于存储文件中的5行内容。相关代码如下:
#include <stdlib.h>
#include <sys/types.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <sys/un.h> /* UNIX domain header */
void FillBuffersForSender();
char buf[5][2000]; //Buffer for 5 frames of output
int main()
{
FillBuffersForSender();
return 0;
}
void FillBuffersForSender(){
FILE *fp;
int line = 0;
char* temp = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("frames.txt", "r");
printf("At the beginning of Fill Buffers loop.\n");
//while ((read = getline(&temp, &len, fp)) != -1){
while(line < 5){
//fprintf(stderr, "Read in: %s\n", temp);
fgets(temp, 2000, fp);
strcpy(buf[line], temp);
line++;
fprintf(stderr, "Line contains: %s.\n", temp);
temp = NULL;
}
while(line != 0){
fprintf(stderr, "Line contains: %s.\n", buf[line]);
line--;
}
}
这行代码
strcpy(buf[line], temp);
代码导致分段错误。我已经尝试过多种方法,但似乎一直无法让它工作。虽然我不熟悉C语言,但任务是要在其中编写双向滑动窗口协议。我一直遇到像这样的超基本问题!如果这是C++,我早就完成了。希望有人能提供帮助,感激不尽。