【发布时间】:2015-03-08 13:38:58
【问题描述】:
所以我有一个文本文件:
5f6
2f8
2f2
我正在读取值:5,6,2,8,2,2 其中前两个数字始终是行 x 列,然后我试图在回顾文件值时绘制矩形(这可以,但是在运行程序并打印它们之后,它会出现错误)。
#include <stdio.h>
#include <ncurses.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char * argv[])
{
initscr();
cbreak();
noecho();
char str[100];
static char * row;
static char * col;
static int i;
static int j;
static int k;
static int x;
static int y;
int count = 0;
FILE* file;
file = fopen(argv[1],"r");
if(file == NULL)
{
mvprintw(0,0,"File returns null pointer");
exit(1);
}
while(!feof(file))
{
fgets(str,100,file);
row = strtok(str,"x");
col = strtok(NULL," \n");
x = atol(row);
y = atol(col);
for(j=0;j<x;j++)
{
for(k=0;k<y;k++)
{
mvprintw(k+5,j+5+count,".");
refresh(); //Space out drawing each rectangle? so they don't overlap
}
}
count+=5;
}
fclose(file);
getch();
endwin();
return (0);
}
我不确定如何在此处继续,我将如何消除此段错误,并可能将生成的绘图隔开(count 变量似乎没有这样做)。
【问题讨论】:
-
使用 while(file!=NULL) 会更好吗?
-
@user3739406 ,改用
while(fgets(str,100,file)) -
@user3739406 只需阅读链接即可了解原因。
-
函数 feof() 在尝试读取文件末尾之后才有效。所以它不应该用在循环控制中。强烈建议使用'while fgets(str, sizeof(str), file)
标签: c arrays file for-loop segmentation-fault