使用fgets和fscanf时C中的分段错误

时间:2015-02-21 20:16:13

标签: c segmentation-fault fgets scanf

我试图读取文本文件的第一行,然后使用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: 固定。代码放置是唯一的问题。

1 个答案:

答案 0 :(得分:3)

您无法检查文件是否已打开,fscanf()fgets()期望有效FILE *您需要检查fopen()的返回值 1 ,您还应确保在命令行中提供了参数,因为您可以在以下代码中检查argc示例

int main(int argc, char **argv)
{
    char  buffer[1024];
    FILE *file;

    if (argc < 2)
    {
        fprintf(stderr, "you need to provide a file name.\n");
        return 1;
    }

    file = fopen(argv[1], "r");
    if (file == NULL) /* problem opening */
    {
        fprintf(stderr, "error openning %s\n", filename);
        return 2;
    }
    if (fgets(buffer, sizeof(buffer), file) != NULL)
        printf("%s\n", buffer);
    fclose(file); /* close the file */
    return 0;
}

上面的代码不会失败,即使用错误数量的参数调用程序或程序无法打开文件,或者它无法从中读取。


<子> 1。当fopen()无法打开文件时,NULL会返回{{1}}。