c - 在 C 中调用 fgets 时出现段错误

标签 c segmentation-fault fgets

我正在用我的 C 代码编写一个函数,要求我的函数在文件中随机搜索由给定数量的字符组成的单词。 这是我的代码:

#include "stdio.h"
#include "stdlib.h"
#include "time.h"
#include "string.h"
void ExtMot(char nom, char *s[80], int n )
{
    FILE *fp ; 
    int i=0, j=0,x ;
    int taille= n  ;
    srand (time (NULL)) ;
    fp = fopen (nom,"r") ;
    while (fgets (s, 80, fp))
    {
        i++ ;
    }

    printf (" enter the size ") ;
    scanf ("%d",&taille) ;
    do
    {
        x= rand ()* rand() % i ; 
        rewind(fp);  
        while (fgets (s, 80, fp))
        {
           j++ ;
           if (j==x) break ;
        }
        s[strlen (s)]='\0' ;
        if (strlen (s)-1 == taille )
            break ;
        else
            j=0 ;
    } while (1) ;
    fclose (fp) ;
}


void main ()
{
   char mot[80];
   ExtMot("C:\\Users\\asus\\Desktop\\c_projet\\hello\\projet.txt",*mot,6);
   printf ("%s",mot);
}

我调试了我的代码,但在调用 fgets 函数和控制台应用程序崩溃时出现了段错误。谁能帮我找出错误?

最佳答案

我想知道您的代码是如何编译的(如果有的话)。对于这些类型错误,您应该一直收到警告。以下调整应该可以使您的代码编译(我使用 -Wall 编译),但我无法证明它的可靠性,因为我不知道您的 hello\projet.txt 文件。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <errno.h>
// these headers were wrapped in quotes "", instead of angle brackets <>

void ExtMot(char *nom, char *s, int n) {
    FILE *fp;
    int j = 0, i, x;
    int taille = n;
    srand(time(NULL));
    if (!(fp = fopen(nom, "r"))) {
        fprintf(stderr, "Could not open file: %s\n", strerror(errno));
        return;
    }
    // always check if the result of fopen == null

    for (i = 0; fgets(s, 80, fp); i++)
        ;

    // rest of the code here...
}

int main(void) {
    char mot[80];
    ExtMot("C:\\Users\\asus\\Desktop\\c_projet\\hello\\projet.txt", mot, 6);
    printf("%s\n", mot);
    return 0;
}

您试图包含带有双引号的 C 标准库 header ,而不是像您应该的那样包含尖括号。如果头文件与源文件位于同一目录中,则仅对包含使用双引号。您似乎对 ExtMot() 的参数中的类型有正确的想法,但它不会按照您期望的方式工作。 char nom 是单个字符。 char *m[80] 是一个包含 80 个字符指针的数组,而不是一个包含 80 个字符的数组。

*mot 是指向 80 个字符数组的指针。 mot 是 80 个字符的数组。因此,您没有将 char 缓冲区发送到 ExtMot(),而是发送了 char 缓冲区在内存中的位置,这将破坏您的代码(并且应该触发来自编译器的警告)。请参阅我上面的代码,了解如何将字符串传递给函数。

编辑:此外,void main() 已过时且糟糕的做法。如果您不需要任何命令行参数,请始终使用 int main(void) 并返回 0。

关于c - 在 C 中调用 fgets 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48039044/

相关文章:

c - C get 行中的段错误

c - C 中的段错误导致代码有时运行但有时不运行

c - 尝试在 C 中读取 txt 文件时出错去分段(核心转储)

C语言不区分大小写地统计某个字符在文件中出现的次数

c - 加密程序交换?

创建一个包含 BST 给定范围内数字的单向链表

子函数 : How do I know what to fix? 中的 C 段错误 什么是段错误?

c - 如何检查值是否与字符串匹配

c - 忽略尾部读取大小受限的输入行

c - fgets 只获取我文件的最后一行