简体   繁体   English

在 c 中使用 fscanf 从文件获取分段错误

[英]Getting segmentation fault while from a file using fscanf in c

int main() {
    FILE *matrix_r;
    matrix_r=fopen("matrix.txt","r");
    double x;char c;
    while(feof(matrix_r)){
        fscanf(matrix_r,"%lf%c",&x,&c);
        printf("%lf%c",x,c);
    }
    fclose(matrix_r);

    return 0;
}

Trying to read float values from the file but getting segmentation fault core dumped error.尝试从文件中读取浮点值但出现分段错误核心转储错误。 matrix.txt stores a matrix of floats. matrix.txt 存储浮点数矩阵。

contents of matrix.txt are below. matrix.txt 的内容如下。

0.000000,876.671546,448.879717,1349.827396
876.671546,0.000000,1319.195209,964.193445
448.879717,1319.195209,0.000000,1741.628261
1349.827396,964.193445,1741.628261,0.000000

fopen() failed and feof(NULL) caused the segfault. fopen()失败, feof(NULL)导致段错误。 If fopen() was successful then feof() would return false and the loop wouldn't run but your program wouldn't segfault.如果fopen()成功,则feof()将返回 false,并且循环不会运行,但您的程序不会出现段错误。

Check the return value of fopen() & fscanf() .检查fopen()fscanf()的返回值。 You only need to call feof() if you need to find out why fscanf() failed to read 2 items.如果您需要找出为什么fscanf()无法读取 2 个项目,则只需调用feof()

#include <stdio.h>

int main() {
    FILE *matrix_r = fopen("matrix.txt", "r");
    if(!matrix_r) {
        perror("fopen");
        return 1;
    }
    for(;;) {
        double x;
        char c;
        int rv = fscanf(matrix_r, "%lf%c", &x, &c);
        if(rv != 2)
            break;
        printf("%lf%c", x, c);
    }
    fclose(matrix_r);
}

Here is the output:这是 output:

0.000000,876.671546,448.879717,1349.827396
876.671546,0.000000,1319.195209,964.193445
448.879717,1319.195209,0.000000,1741.628261
1349.827396,964.193445,1741.628261,0.000000
  1. You do not check if fopen was successful.您不检查fopen是否成功。 Calls to feof or fscanf if the file pointer is NULL invoke Undefined Behaviour如果文件指针为 NULL,则调用feoffscanf调用未定义行为

  2. while(feof(matrix_r)){

while(.feof(...))) is always wrong ( Why is “while(?feof(file) )” always wrong? ), but your one has no logical sense at all (as you want to scanf if it is the end of the file). while(.feof(...)))总是错的( 为什么“while(?feof(file) )”总是错的? ),但你的那个根本没有逻辑意义(因为你想scanf它是否是文件末尾)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM