【发布时间】:2014-12-05 01:20:29
【问题描述】:
这是我在这里提出的第一个问题,所以如果我没有遵循此处的格式规则,请原谅我。我正在用 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++ 中,我已经完成了。任何人都能提供的任何帮助都是不可思议的。谢谢你。
【问题讨论】: