简体   繁体   English

当我运行 a.out 时,代码会出现分段错误,在 linux 终端中使用 C,访问具有适当权限的文件

[英]Code gives a segmentation fault when I run a.out, using C in a linux terminal, accessing files that were given proper permissions

/* Your Name  Brenton                              */
/* Lab 4                                           */
/* Figure the area of the top of a cylinder        */
/* and the volume of a cylinder                    */

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

//#define FILE_IN  "lab4.dat"
#define FILE_IN  "lab4sample.dat"

int main(void)
{

    printf("Brenton Kludt, Lab 4");
    int count = 1;
    double radius, height, area, vol;

    FILE * input_file;
    FILE * output_file; 

    input_file = fopen ("lab4sample.dat", "r");
    if(input_file == NULL){
        printf("Error on opening the input file \n");
        exit (EXIT_FAILURE);
    }

    output_file = fopen ("lab4.out", "w");
    if(output_file == NULL){
        printf("Error on opening the output file");
        exit (EXIT_FAILURE);
    }

    fprintf(output_file, "\nBrenton Kludt. Lab 4.");
    while ((fscanf(input_file, "%lf%lf%lf", &radius, &height)) == 2)
    {
        vol = radius * height;
        area   = M_PI * radius * radius;

        fprintf(output_file, "\nCylinder %1d", count);
            fprintf(output_file, "\nThe radius is:    %9.3f", radius);
            fprintf(output_file, "\nThe height is:    %9.3f", height);
            fprintf(output_file, "\nThe top area is:  %9.3f", area);
            fprintf(output_file, "\nThe volume is:    %9.3f\n", vol);
            count++;

    }
    fclose(input_file);
    fclose(output_file);

    return EXIT_SUCCESS;


}

Everything compiles correctly.一切都正确编译。 The code is being used to access a file that has a set of data, to which, it was process it, and create an formatted output file.该代码用于访问具有一组数据的文件,并对其进行处理,并创建格式化的输出文件。 I used gcc -lm thisfile.c, to which an a.out is created, and when I run a.out, it hangs and gives me a segmentation fault after about 10 seconds.我使用了 gcc -lm thisfile.c,创建了 a.out,当我运行 a.out 时,它挂起并在大约 10 秒后给我一个分段错误。 Is the problem within the code, or is the problem with permissions?是代码问题,还是权限问题?

将 3 个值读入 2 个变量(和 null)可能是我猜测的原因。

fscanf(input_file, "%lf%lf%lf", &radius, &height)

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

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