gpt4 book ai didi

c - 读入文件导致段错误

转载 作者:太空宇宙 更新时间:2023-11-04 08:29:49 26 4
gpt4 key购买 nike

所以我有一个文本文件:

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 变量似乎无法做到这一点)。

最佳答案

您的段错误是因为您没有检查 strtok() 是否返回了 NULL 并且您仍然使用 atol() 取消引用指针,这是如何正确执行此操作的示例

#include <stdio.h>
#include <ncurses.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char * argv[])
{
char str[100];
int j;
int k;
int count;
FILE *file;

file = fopen(argv[1],"r");
if (file == NULL)
{
mvprintw(0, 0, "File returns null pointer");
return 1;
}

initscr();
cbreak();
noecho();

count = 0;
while(fgets(str, sizeof(str), file) != NULL)
{
char *endptr;
char *row;
char *col;
int x;
int y;

row = strtok(str, "f");
if (row == NULL)
{
fprintf(stderr, "`%s' does not contain `f'\n", str);
continue;
}
col = strtok(NULL, " \n");
if (col == NULL)
{
fprintf(stderr, "`%s' caused an unexpected error\n", str);
continue;
}
x = strtol(row, &endptr, 10);
if (*endptr != '\0')
{
fprintf(stderr, "Cannot convert `%s' to integer\n", row);
continue;
}
y = strtol(col, &endptr, 10);
if (*endptr != '\0')
{
fprintf(stderr, "Cannot convert `%s' to integer\n", col);
continue;
}
for (j = 0 ; j < x ; j++)
{
for (k = 0 ; k < y ; k++)
{
mvprintw(k + 5, j + 5 + count, ".");
refresh();
}
}
count+=5;
}

fclose(file);
getch();
endwin();

return 0;
}

关于c - 读入文件导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28927068/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com