首页 > 解决方案 > 如何使用 fgets() 和输入文件在 c 中打开文件?

问题描述

我正在尝试打开输入文件 [100] 指示的文件。我不断收到分段错误。我知道 fgets() 函数存在一些问题,但我不确定它是什么。我无法在循环中运行任何代码。最终代码应该从文本文件的第一行获取文件,但它不起作用。任何帮助将不胜感激,如果需要,我可以发布主要功能代码!

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


    char *getCoeff(char file[100], char chemName[50])
    {
            FILE* fptr = fopen(file, "r");
            char data[80];
            char *dataptr = data;
            char line[80];
            int count = 0;
            int i = 0;
            printf("%s",file);

            while (fgets(line, sizeof line, fptr) != NULL)
            {
                     printf("Inside loop\n");
                     printf("%s",line);
                     strcpy(data,line);

             }
             fclose(fptr);

             return dataptr;
    }

标签: csegmentation-faultfgets

解决方案


推荐阅读