【发布时间】:2023-03-20 07:27:02
【问题描述】:
我正在尝试读取文本文件的第一行,然后使用 fgets 跳过它,但它给了我一个 seg 错误,有人可以帮助我吗?在我添加 fgets 之前它已经工作了,因此 fgets 似乎是问题所在。
代码
#include <stdio.h>
#include <stdlib.h>
#include <sched.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int N
const int STACK_SIZE=65536;
int col=0;
int i;
int j;
FILE *file1;
int s;
int row=0;
int prev='t';
char m[1024];
if(argc != 3)
{
fprintf(stderr, "Usage: %s <Executable> <Input file> <Threads>\n", argv[0]);
exit(1);
}
file1=fopen(argv[1],"r");
if(file1==NULL) //check to see if file exists
{
fprintf(stderr, "Cannot open %s\n", argv[1]);
exit(1);
}
stack=malloc(STACK_SIZE);
if(stack==NULL)
{
perror("malloc");
exit(1);
}
if(atoi(argv[2]) == 0)
{
fprintf(stderr,"Threads has to be a number.\n");
exit(1);
}
fscanf(file1,"%d",&N);
rewind(file1);
fgets(m,sizeof(m),file1);
while((s=fgetc(file1)) != EOF)
{
if(s == ' ')
{
prev='a';
continue;
}
if(s == '\n' && prev != '\n')
{
row++;
if(col != N)
{
fprintf(stderr, "File %s has incorrect columns.\n", argv[1]);
exit(1);
}
col=0;
prev='a';
}
if(s != ' ' && s != '\n')
{
col++;
prev='a';
}
}
if(row != N)
{
fprintf(stderr,"File %s has incorrect rows.\n", argv[1]);
exit(0);
}
rewind(file1);
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
fscanf(file1,"%d",&A[i][j]);
}
}
fclose(file1);
}
}
编辑 1: 固定的。代码放置是唯一的问题。
【问题讨论】:
-
您的 real 代码检查
file1是否为 NULL,以在将文件发送到fscanf或fgets之前验证打开的文件,right我> ?? “假设是一切之母......” -
@WhozCraig 是的,我在我的真实代码中检查了它
-
然后发布您的“真实”代码,包括
#include列表和可编译的main(),并注释标记调试器中报告段错误的确切行。还要验证arg[1]实际上是一个实际的空项字符串指针,并且argc至少是 2。 -
@AndrewChan 不要发布一些您认为有问题的代码,当问题出在您的真实代码中时,现在我给了您两个错误的答案。而且新代码也有一些可疑之处,您需要发布真实问题的可重现样本。
-
如果
argc < 3会怎样?还有exit(1)每次出错都不好,需要先清理一下。
标签: c segmentation-fault fgets scanf